package com.uzai.console.service.configplan.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.entity.WechatUser;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.enums.DeviceTypeGroupEnum;
import com.uzai.common.enums.MessageFuncEnum;
import com.uzai.common.enums.RedisCacheKeyEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.msg.MsgDto;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.CommonUtil;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.DesensitizeUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.constant.Const;
import com.uzai.console.dto.device.DeviceQuery;
import com.uzai.console.dto.dy.dytoken.DyTokenQuery;
import com.uzai.console.dto.feign.usertakebal.CashierAppCheckDto;
import com.uzai.console.dto.jd.jdtoken.JdTokenQuery;
import com.uzai.console.dto.locallive.tlbtoken.TlbTokenQuery;
import com.uzai.console.dto.pdd.pddtoken.PddTokenQuery;
import com.uzai.console.dto.profit.normalrewardrule.NormalRewardRuleQuery;
import com.uzai.console.dto.profit.regrewardrule.RegRewardRuleQuery;
import com.uzai.console.dto.rocketmq.androidapp.AndroidSetConfigDto;
import com.uzai.console.dto.rocketmq.configplan.BigPromotionDto;
import com.uzai.console.dto.rocketmq.configplan.ClientSetDto;
import com.uzai.console.dto.sysdomain.SysDomainQuery;
import com.uzai.console.dto.tb.tbtoken.TbTokenQuery;
import com.uzai.console.dto.user.usertype.UserTypeQuery;
import com.uzai.console.dto.user.wechatuser.WechatUserQuery;
import com.uzai.console.dto.vph.vphtoken.VphTokenQuery;
import com.uzai.console.dto.wechatprivate.configplan.*;
import com.uzai.console.dto.wechatprivate.devicewechatinfo.DeviceWechatInfoQuery;
import com.uzai.console.entity.*;
import com.uzai.console.mapper.*;
import com.uzai.console.service.configplan.ConfigPlanService;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.feign.UserTakeBalFeignService;
import com.uzai.console.service.feign.UzaiImClientFeignService;
import com.uzai.console.service.rebotcmd.RobotCmdService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.user.UserService;
import com.uzai.console.service.wechatapp.AppDeviceInfoService;
import com.uzai.console.vo.base.SelectIdVo;
import com.uzai.console.vo.base.SelectKeyVo;
import com.uzai.console.vo.device.DeviceInfoVo;
import com.uzai.console.vo.sysdomain.SysDomainInfoVo;
import com.uzai.console.vo.sysplugin.SysPluginVo;
import com.uzai.console.vo.wechatprivate.configplan.BigPromotionVo;
import com.uzai.console.vo.wechatprivate.configplan.ConfigPlanSelectListVo;
import com.uzai.console.vo.wechatprivate.configplan.ConfigPlanVo;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.C;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author liuqi
 * @date 2021年08月23日 20:25
 */
@Service
public class ConfigPlanServiceImpl implements ConfigPlanService {

    Logger logger = LoggerFactory.getLogger(ConfigPlanServiceImpl.class);

    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private SysPluginMapper sysPluginMapper;
    @Autowired
    private TbTokenMapper tbTokenMapper;
    @Autowired
    private JdTokenMapper jdTokenMapper;
    @Autowired
    private VphTokenMapper vphTokenMapper;
    @Autowired
    private PddTokenMapper pddTokenMapper;
    @Autowired
    private DyTokenMapper dyTokenMapper;
    @Autowired
    private NormalRewardRuleMapper normalRewardRuleMapper;
    @Autowired
    private RegRewardRuleMapper regRewardRuleMapper;
    @Autowired
    private SysDomainMapper sysDomainMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RobotCmdService robotCmdService;
    @Autowired
    private RobotCmdMapper robotCmdMapper;
    @Autowired
    private UserTypeMapper userTypeMapper;
    @Autowired
    private WechatUserMapper wechatUserMapper;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private TlbTokenMapper tlbTokenMapper;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private UzaiImClientFeignService uzaiImClientFeignService;
    @Autowired
    private UserTakeBalFeignService userTakeBalFeignService;
    @Autowired
    private AppDeviceInfoService appDeviceInfoService;
    @Autowired
    private MerchantMapper merchantMapper;


    /**
     * 查询配置方案下拉列表
     *
     * @param query
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public List<ConfigPlanSelectListVo> findConfigPlanSelectList(ConfigPlanQuery query) {

        //新建返回配置方案下拉列表
        ArrayList<ConfigPlanSelectListVo>  selectList = new ArrayList<ConfigPlanSelectListVo>();
        //查询数据库中的配置方案
        ArrayList<ConfigPlan> configPlanList = configPlanMapper.findByList(query);
        if(configPlanList != null && configPlanList.size() > 0){
            for (ConfigPlan configPlan : configPlanList){
                ConfigPlanSelectListVo selectListVo = new ConfigPlanSelectListVo();
                BeanUtils.copyProperties(configPlan, selectListVo);
                selectList.add(selectListVo);
            }
        }

        return selectList;
    }

    /**
     * 查询配置方案详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param configPlanIdDto
     * @return null
     */
    public ConfigPlanVo findConfigPlanInfo(ConfigPlanIdDto configPlanIdDto){
        if(configPlanIdDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        //查询配置方案信息
        ConfigPlan configPlan = configPlanMapper.selectById(configPlanIdDto.getId(), configPlanIdDto.getMerId());
        if(configPlan == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该配置方案不存在");
        }
        //返回页面列表
        ConfigPlanVo configPlanVo = new ConfigPlanVo();
        //对象复制
        BeanUtils.copyProperties(configPlan, configPlanVo);

        return configPlanVo;
    }

    /**
     * 查询默认配置方案详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @param deviceType
     * @return null
     */
    public ConfigPlanVo findConfigPlanInfoIsDefault(Long merId, String deviceType){
        if(merId == null || StringUtils.isBlank(deviceType)){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        //返回页面列表
        ConfigPlanVo configPlanVo = new ConfigPlanVo();

        //查询配置方案信息
        ConfigPlan configPlan = configPlanMapper.selectByIsDefault(merId, deviceType);
        if(configPlan != null) {
            //对象复制
            BeanUtils.copyProperties(configPlan, configPlanVo);
        }
        return configPlanVo;
    }

    /**
     * 复制默认配置方案详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param configPlanCopyDefaultDto
     * @return null
     */
    public ConfigPlanVo copyDefaultConfig(ConfigPlanCopyDefaultDto configPlanCopyDefaultDto){
        Long merId = configPlanCopyDefaultDto.getMerId();
        //来源（0-官方默认配置方案；1-个人微信默认配置方案）
        Integer source = configPlanCopyDefaultDto.getSource();
        String deviceType = configPlanCopyDefaultDto.getDeviceType();

        if(merId == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统参数错误");
        }
        if(source == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择复制配置来源");
        }
        if(StringUtils.isBlank(deviceType)){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择设备类型");
        }

        //返回页面列表
        ConfigPlanVo configPlanVo = new ConfigPlanVo();

        ConfigPlan configPlan_default = null;
        if(source.intValue() == 0){//官方默认配置方案
            Long defaultMerId = uzaiConsoleSysConfig.getDefaultMerId();
            configPlan_default = configPlanMapper.selectByIsDefault(defaultMerId, deviceType);
        }else if(source.intValue() == 1){//1-个人微信默认配置方案
            configPlan_default = configPlanMapper.selectByIsDefault(merId, DeviceTypeEnum.DT_PC_WECHAT.getKey());
        }

        if(configPlan_default != null) {
            int now = DateUtil.getNowTime();

            //复制插件件信息
            List<SysPlugin> sysPluginsList = new ArrayList<>();
            Long configPlanId = IdWorker.getId();

            //淘宝插件ID
            if (configPlan_default.getTbId() != null) {
                //查询淘宝插件
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan_default.getTbId(), configPlan_default.getMerId());
                if (sysPlugin != null) {
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(merId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案的淘宝插件
                    configPlan_default.setTbId(id);
                }
            }

            //京东插件id
            if (configPlan_default.getJdId() != null) {
                //查询京东插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan_default.getJdId(), configPlan_default.getMerId());
                if (sysPlugin != null) {
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(merId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加京东插件id
                    //sysPluginMapper.insert(sysPlugin);
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案的京东插件id
                    configPlan_default.setJdId(id);
                }
            }

            //拼多多插件id
            if (configPlan_default.getPddId() != null) {
                //查询拼多多插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan_default.getPddId(), configPlan_default.getMerId());
                if (sysPlugin != null) {
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(merId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加拼多多插件id
                    //sysPluginMapper.insert(sysPlugin);
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案的拼多多插件id
                    configPlan_default.setPddId(id);
                }
            }

            //唯品会插件id
            if (configPlan_default.getVphId() != null) {
                //查询唯品会插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan_default.getVphId(), configPlan_default.getMerId());
                if (sysPlugin != null) {
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(merId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加唯品会插件id
                    //sysPluginMapper.insert(sysPlugin);
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案的唯品会插件id
                    configPlan_default.setVphId(id);
                }
            }

            //本地生活插件id
            if (configPlan_default.getLocalLiveId() != null) {
                //查询本地生活插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan_default.getLocalLiveId(), configPlan_default.getMerId());
                if (sysPlugin != null) {
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(merId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加本地生活插件id
                    //sysPluginMapper.insert(sysPlugin);
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案的本地生活插件id
                    configPlan_default.setLocalLiveId(id);

                    //本地生活指令
                    //robotCmdService.addRobotCmdForConfigPlan(configPlan.getMerId(), configPlan.getId(), PluginKeyEnum.LOCAL_LIVE.getValue(), sysPlugin.getData());
                }
            }

            //抖音插件id
            if (configPlan_default.getDyId() != null) {
                //查询唯品会插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan_default.getDyId(), configPlan_default.getMerId());
                if (sysPlugin != null) {
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(merId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加唯品会插件id
                    //sysPluginMapper.insert(sysPlugin);
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案的唯品会插件id
                    configPlan_default.setDyId(id);
                }
            }

            //更新分佣规则
            //会员类型组
            configPlan_default.setUserTypeGroupId(null);
            //淘宝分佣规则
            configPlan_default.setTbCommissionPlanId(null);
            //京东分佣规则
            configPlan_default.setJdCommissionPlanId(null);
            //拼多多分佣规则
            configPlan_default.setPddCommissionPlanId(null);
            //唯品会分佣规则
            configPlan_default.setVphCommissionPlanId(null);
            //本地生活分佣规则
            configPlan_default.setLocalLiveCommissionPlanId(null);

            //拉群规则
            if (configPlan_default.getPullWxgroupRuleId() != null) {
                //查询微信好友添加插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan_default.getPullWxgroupRuleId(), configPlan_default.getMerId());
                if (sysPlugin != null) {
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(merId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加微信好友添加插件id
                    //sysPluginMapper.insert(sysPlugin);
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案的微信好友添加插件id
                    configPlan_default.setPullWxgroupRuleId(id);
                }
            }

            //微信好友添加插件id
            if (configPlan_default.getWxUserAddId() != null) {
                //查询微信好友添加插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan_default.getWxUserAddId(), configPlan_default.getMerId());
                if (sysPlugin != null) {
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(merId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加微信好友添加插件id
                    //sysPluginMapper.insert(sysPlugin);
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案的微信好友添加插件id
                    configPlan_default.setWxUserAddId(id);
                }
            }

            //推广裂变插件id
            if (configPlan_default.getUserExpandFissionId() != null) {
                //查询推广裂变插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan_default.getUserExpandFissionId(), configPlan_default.getMerId());
                if (sysPlugin != null) {
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(merId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加推广裂变插件id
                    //sysPluginMapper.insert(sysPlugin);
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案的推广裂变插件id
                    configPlan_default.setUserExpandFissionId(id);
                }
            }
            //提现插件id
            if (configPlan_default.getUserTakeBalId() != null) {
                //查询提现插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan_default.getUserTakeBalId(), configPlan_default.getMerId());
                if (sysPlugin != null) {
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(merId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加提现插件id
                    //sysPluginMapper.insert(sysPlugin);
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案中提现插件id
                    configPlan_default.setUserTakeBalId(id);

                    //保存提现指令
                    //robotCmdService.addRobotCmdForConfigPlan(configPlan.getMerId(), configPlan.getId(), PluginKeyEnum.USER_TAKE_BAL.getValue(), sysPlugin.getData());
                }
            }
            //好友引导插件id
            if (configPlan_default.getUserGuideId() != null) {
                //好友引导插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan_default.getUserGuideId(), configPlan_default.getMerId());
                if (sysPlugin != null) {
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(merId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加好友引导插件id
                    //sysPluginMapper.insert(sysPlugin);
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案中好友引导插件id
                    configPlan_default.setUserGuideId(id);
                }
            }
            //自动备注插件id
            if (configPlan_default.getUserAutoRemarkId() != null) {
                //自动备注插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan_default.getUserAutoRemarkId(), configPlan_default.getMerId());
                if (sysPlugin != null) {
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(merId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加自动备注插件id
                    //sysPluginMapper.insert(sysPlugin);
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案中自动备注插件id
                    configPlan_default.setUserAutoRemarkId(id);
                }
            }

            //订阅消息插件id
            if (configPlan_default.getSubscribeMsgId() != null) {
                //订阅消息插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan_default.getSubscribeMsgId(), configPlan_default.getMerId());
                if (sysPlugin != null) {
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(merId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加订阅消息插件id
                    //sysPluginMapper.insert(sysPlugin);
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案中订阅消息插件id
                    configPlan_default.setSubscribeMsgId(id);

                    //保存订阅指令
                    //robotCmdService.addRobotCmdForConfigPlan(configPlan.getMerId(), configPlan.getId(), PluginKeyEnum.SUBSCRIBE_MSG.getValue(), sysPlugin.getData());
                }
            }

            //个人信息查询插件id
            if (configPlan_default.getUserInfoQueryId() != null) {
                //订阅消息插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan_default.getUserInfoQueryId(), configPlan_default.getMerId());
                if (sysPlugin != null) {
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(merId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加个人信息查询插件id
                    //sysPluginMapper.insert(sysPlugin);
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案中个人信息查询插件id
                    configPlan_default.setUserInfoQueryId(id);

                    //保存个人信息指令
                    //robotCmdService.addRobotCmdForConfigPlan(configPlan.getMerId(), configPlan.getId(), PluginKeyEnum.USER_INFO_QUERY.getValue(), sysPlugin.getData());
                }
            }

            //用户签到插件id
            if (configPlan_default.getUserSigninId() != null) {
                //用户签到插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan_default.getUserSigninId(), configPlan_default.getMerId());
                if (sysPlugin != null) {
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(merId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加用户签到插件id
                    //sysPluginMapper.insert(sysPlugin);
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案中用户签到插件id
                    configPlan_default.setUserSigninId(id);

                    //保存用户签到指令
                    //robotCmdService.addRobotCmdForConfigPlan(configPlan.getMerId(), configPlan.getId(), PluginKeyEnum.USER_SIGNIN.getValue(), sysPlugin.getData());

                }
            }
            //社群管理插件id
            if (configPlan_default.getCommunityId() != null) {
                //社群管理插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan_default.getCommunityId(), configPlan_default.getMerId());
                if (sysPlugin != null) {
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(merId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加社群管理插件id
                    //sysPluginMapper.insert(sysPlugin);
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案中社群管理插件id
                    configPlan_default.setCommunityId(id);

                    //保存社群指令
                    //robotCmdService.addRobotCmdForConfigPlan(configPlan.getMerId(), configPlan.getId(), PluginKeyEnum.COMMUNITY.getValue(), sysPlugin.getData());
                }
            }

            //其他设置插件id
            if (configPlan_default.getOtherId() != null) {
                //其他设置插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan_default.getOtherId(), configPlan_default.getMerId());
                if (sysPlugin != null) {
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(merId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加其他设置插件id
                    //sysPluginMapper.insert(sysPlugin);
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案中其他设置插件id
                    configPlan_default.setOtherId(id);
                }
            }

            //导购插件id
            if (configPlan_default.getShoppingGuideId() != null) {
                //社群管理插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan_default.getShoppingGuideId(), configPlan_default.getMerId());
                if (sysPlugin != null) {
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(merId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加社群管理插件id
                    //sysPluginMapper.insert(sysPlugin);
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案中社群管理插件id
                    configPlan_default.setShoppingGuideId(id);

                    //保存社群指令
                    //robotCmdService.addRobotCmdForConfigPlan(configPlan.getMerId(), configPlan.getId(), PluginKeyEnum.COMMUNITY.getValue(), sysPlugin.getData());
                }
            }

            //微信公众号设置id
            if (configPlan_default.getWxpubSettingId() != null) {
                //其他设置插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan_default.getWxpubSettingId(), configPlan_default.getMerId());
                if (sysPlugin != null) {
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加其他设置插件id
                    //sysPluginMapper.insert(sysPlugin);
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案中其他设置插件id
                    configPlan_default.setWxpubSettingId(id);
                }
            }

            //微信机器人关联公众号插件id
            if (configPlan_default.getWechatUnionWxpubId() != null) {
                //其他设置插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan_default.getWechatUnionWxpubId(), configPlan_default.getMerId());
                if (sysPlugin != null) {
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加其他设置插件id
                    //sysPluginMapper.insert(sysPlugin);
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案中其他设置插件id
                    configPlan_default.setWechatUnionWxpubId(id);
                }
            }

            //批量插入插件
            if (sysPluginsList != null & sysPluginsList.size() > 0) {
                sysPluginMapper.batchAdd(sysPluginsList);
                for (SysPlugin sysPlugin : sysPluginsList) {
                    //修改插件更新缓存，确保缓存和数据库一致
                    redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.PLUGIN.getKey(), sysPlugin.getId()), sysPlugin.getData(), 5, TimeUnit.DAYS);
                }
            }

            //查出旧指令列表
            List<RobotCmd> robotCmdList = robotCmdMapper.selectByConfigId(configPlan_default.getMerId(), configPlan_default.getId());
            if (robotCmdList != null && robotCmdList.size() > 0) {
                for (RobotCmd robotCmd : robotCmdList) {
                    robotCmd.setId(IdWorker.getId()); //更新旧指令ID
                    robotCmd.setMerId(merId);
                    robotCmd.setConfigId(configPlanId);//更新旧指令配置方案
                    robotCmd.setCreateTime(now);
                    robotCmd.setUpdateTime(now);
                }

                //批量插入指令表数据库
                robotCmdMapper.batchAdd(robotCmdList);

                //更新新的指令缓存redis
                String data = Tools.getStrEmpty(JSONObject.toJSONString(robotCmdList));
                redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.COMMAND_LIST.getKey(), configPlanId), data);

            }

            //添加新的配置方案
            configPlan_default.setId(configPlanId);
            String name_old = configPlan_default.getName();
            String name_new = configPlan_default.getName() + "(副本" + CommonUtil.random(100, 999) + ")";
            configPlan_default.setName(name_new);
            configPlan_default.setMerId(merId);
            configPlan_default.setCreateTime(now);
            configPlan_default.setUpdateTime(now);
            configPlan_default.setIsDefault(1);
            configPlan_default.setDeviceType(deviceType);

            //清除联盟设置
            configPlan_default.setTbAccountId(null);
            configPlan_default.setJdAccountId(null);
            configPlan_default.setPddAccountId(null);
            configPlan_default.setVphAccountId(null);
            configPlan_default.setTlbPddAccountId(null);
            configPlan_default.setTlbMtAccountId(null);
            configPlan_default.setElmAccountId(null);
            configPlan_default.setDyAccountId(null);

            configPlanMapper.insert(configPlan_default);

            //对象复制
            BeanUtils.copyProperties(configPlan_default, configPlanVo);
        }

        return configPlanVo;

    }


    /**
     * 添加配置方案详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param configPlanAddDto
     * @return null
     */
    public Long addConfigPlan(ConfigPlanAddDto configPlanAddDto){

        if(configPlanAddDto.getMerId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请先登录系统");
        }

        if(StringUtils.isBlank(Tools.getStr(configPlanAddDto.getName())) || StringUtils.isBlank(Tools.getStr(configPlanAddDto.getDeviceType()))){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //验证名称重复
        ConfigPlan configPlan_name = configPlanMapper.selectByNameAndMerIdAndDeviceType(configPlanAddDto.getName(), configPlanAddDto.getMerId(), configPlanAddDto.getDeviceType());
        if(configPlan_name != null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "名称重复");
        }

        Integer now = DateUtil.getNowTime();
        ConfigPlan configPlan = new ConfigPlan();
        Long id = IdWorker.getId();
        configPlan.setId(id);
        configPlan.setDeviceType(configPlanAddDto.getDeviceType());
        configPlan.setMerId(configPlanAddDto.getMerId());
        configPlan.setName(configPlanAddDto.getName());
        configPlan.setCreateTime(now);
        configPlan.setUpdateTime(now);

        //查询数据库是否有默认
        ConfigPlan configPlanIsDefault = configPlanMapper.selectByIsDefault(configPlanAddDto.getMerId(), configPlanAddDto.getDeviceType());
        if(configPlanIsDefault == null){
            configPlan.setIsDefault(1);
        }else{
            configPlan.setIsDefault(0);
        }

        //查询是否有默认的分佣规则
        NormalRewardRule normalRewardRule_default = normalRewardRuleMapper.selectByIsDefault(configPlanAddDto.getMerId());
        //有默认的分佣规则
        if(normalRewardRule_default != null){
            configPlan.setUserTypeGroupId(normalRewardRule_default.getUserTypeGroupId());
            configPlan.setTbCommissionPlanId(normalRewardRule_default.getId());
            configPlan.setJdCommissionPlanId(normalRewardRule_default.getId());
            configPlan.setPddCommissionPlanId(normalRewardRule_default.getId());
            configPlan.setVphCommissionPlanId(normalRewardRule_default.getId());
            configPlan.setDyCommissionPlanId(normalRewardRule_default.getId());
            configPlan.setLocalLiveCommissionPlanId(normalRewardRule_default.getId());
        }

        //如果群管理功能设置配置方案，默认添加群管理功能设置插件
        if(DeviceTypeGroupEnum.PRIVATE_WECHAT_GROUP.getKey().equals(configPlanAddDto.getDeviceType())
                || DeviceTypeGroupEnum.WORK_WECHAT_GROUP.getKey().equals(configPlanAddDto.getDeviceType())
                || DeviceTypeGroupEnum.TIKTOK_GROUP.getKey().equals(configPlanAddDto.getDeviceType()) ){
            Long groupBasesetId = IdWorker.getId();
            SysPlugin sysPlugin = new SysPlugin();
            sysPlugin.setId(groupBasesetId);
            sysPlugin.setMerId(configPlan.getMerId());
            sysPlugin.setPlugName("group_baseset");
            sysPlugin.setData("{\"qgSwitch\":1,\"flSwitch\":0,\"mdSwitch\":0,\"fdSwitch\":0,\"allow_group_replies\":0}");
            sysPlugin.setUpdateTime(now);
            sysPlugin.setCreateTime(now);
            sysPluginMapper.insert(sysPlugin);

            //个人微信群设置
            if(configPlan.getDeviceType().equals(DeviceTypeGroupEnum.PRIVATE_WECHAT_GROUP.getKey())){
                String redisKey_groupmanageplan = String.format(RedisCacheKeyEnum.WXQ_MANAGEPLAN.getKey(), configPlan.getId());
                redisTemplate.opsForValue().set(redisKey_groupmanageplan, sysPlugin.getData());
            }else if(configPlan.getDeviceType().equals(DeviceTypeGroupEnum.WORK_WECHAT_GROUP.getKey())){//企业微信群设置
                String redisKey_groupmanageplan = String.format(RedisCacheKeyEnum.WXQ_WORK_MANAGEPLAN.getKey(), configPlan.getId());
                redisTemplate.opsForValue().set(redisKey_groupmanageplan, sysPlugin.getData());
            }else if(configPlan.getDeviceType().equals(DeviceTypeGroupEnum.TIKTOK_GROUP.getKey())){//抖音群设置
                String redisKey_groupmanageplan = String.format(RedisCacheKeyEnum.TIKTOK_MANAGEPLAN.getKey(), configPlan.getId());
                redisTemplate.opsForValue().set(redisKey_groupmanageplan, sysPlugin.getData());
            }

            //设置群功能插件id
            configPlan.setGroupBasesetId(groupBasesetId);
        }
        //保存数据库
        configPlanMapper.insert(configPlan);

        //返回到前台
        return id;
    }

    /**
     * 修改配置方案详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param configPlanUpdateDto
     * @return null
     */
    public void updateConfigPlan(ConfigPlanUpdateDto configPlanUpdateDto){

        if(configPlanUpdateDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        if(configPlanUpdateDto.getName() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        ConfigPlan configPlan_old = configPlanMapper.selectById(configPlanUpdateDto.getId(), configPlanUpdateDto.getMerId());
        if(configPlan_old == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该配置方案不存在");
        }

        //验证新名字是否已经存在
        if(!configPlan_old.getName().equals(configPlanUpdateDto.getName())){ //表示修改了名称
            //验证新名称是否存在
            ConfigPlan configPlan_name = configPlanMapper.selectByNameAndMerIdAndDeviceType(configPlanUpdateDto.getName(), configPlan_old.getMerId(), configPlan_old.getDeviceType());
            if(configPlan_name != null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "名称重复");
            }
        }

        //配置方案名称
        configPlan_old.setName(configPlanUpdateDto.getName());
        //修改时间
        configPlan_old.setUpdateTime(DateUtil.getNowTime());
        //保存数据库
        configPlanMapper.updateByIdSelective(configPlan_old);
    }

    /**
     * 设置默认配置方案
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param configPlanUpdateDto
     * @return null
     */
    @Transactional
    public void setDefault(ConfigPlanUpdateDto configPlanUpdateDto){

        if(configPlanUpdateDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        ConfigPlan configPlan = configPlanMapper.selectById(configPlanUpdateDto.getId(), configPlanUpdateDto.getMerId());
        if(configPlan == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该配置方案不存在");
        }

        Integer now = DateUtil.getNowTime();

        //将已经存在的默认配置改成非默认
        ConfigPlan configPlan_default = configPlanMapper.selectByIsDefault(configPlan.getMerId(), configPlan.getDeviceType());

        if(configPlan_default != null) {
            configPlan_default.setIsDefault(0);
            configPlan_default.setUpdateTime(now);
            configPlanMapper.update(configPlan_default);
        }

        //设置新的默认
        configPlan.setIsDefault(1);
        configPlan.setUpdateTime(now);
        configPlanMapper.updateByIdSelective(configPlan);
    }

    /**
     * 删除配置方案详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param configPlanIdDto
     * @return null
     */
    @Transactional
    public void deleteConfigPlan(ConfigPlanIdDto configPlanIdDto){

        if(configPlanIdDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        //将配置方案查询出来
        ConfigPlan configPlan =  configPlanMapper.selectById(configPlanIdDto.getId(), configPlanIdDto.getMerId());
        if(configPlan == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该配置方案不存在");
        }

        if(configPlan.getIsDefault().intValue() == 1){ //默认的配置方案
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "不能删除默认的配置方案");
        }

        //先判断是否有机器人在使用该配置，如果有则无法删除
        DeviceQuery deviceQuery = new DeviceQuery();
        deviceQuery.setMerId(configPlanIdDto.getMerId());
        deviceQuery.setDeviceType(configPlan.getDeviceType());
        deviceQuery.setConfigId(configPlan.getId());
        List<DeviceInfoVo> deviceList = deviceService.findDeviceList(deviceQuery);
        if(deviceList != null && deviceList.size() > 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该配置方案已经有机器人在使用，不能删除");
        }

        //批量删除用
        List<Long> idList = new ArrayList<Long>();

        //删除淘宝插件ID
        if(configPlan.getTbId() != null ){
            //sysPluginMapper.deleteById(configPlan.getTbId());
            idList.add(configPlan.getTbId());
        }
        //删除京东插件id
        if(configPlan.getJdId() != null ){
            //sysPluginMapper.deleteById(configPlan.getJdId());
            idList.add(configPlan.getJdId());
        }
        //删除拼多多插件id
        if(configPlan.getPddId() != null ){
            //sysPluginMapper.deleteById(configPlan.getPddId());
            idList.add(configPlan.getPddId());
        }
        //删除唯品会插件id
        if(configPlan.getVphId() != null ){
            //sysPluginMapper.deleteById(configPlan.getVphId());
            idList.add(configPlan.getVphId());
        }
        //删除抖音插件id
        if(configPlan.getDyId() != null ){
            //sysPluginMapper.deleteById(configPlan.getVphId());
            idList.add(configPlan.getDyId());
        }
        //删除本地生活插件id
        if(configPlan.getLocalLiveId() != null ){
            //sysPluginMapper.deleteById(configPlan.getLocalLiveId());
            idList.add(configPlan.getLocalLiveId());
        }
        //删除微信好友添加插件id
        if(configPlan.getWxUserAddId() != null ){
            //sysPluginMapper.deleteById(configPlan.getWxUserAddId());
            idList.add(configPlan.getWxUserAddId());
        }
        //删除好友引导插件id
        if(configPlan.getUserGuideId() != null ){
            //sysPluginMapper.deleteById(configPlan.getUserGuideId());
            idList.add(configPlan.getUserGuideId());
        }
        //删除推广裂变插件id
        if(configPlan.getUserExpandFissionId() != null ){
            //sysPluginMapper.deleteById(configPlan.getUserExpandFissionId());
            idList.add(configPlan.getUserExpandFissionId());
        }
        //删除自动备注插件id
        if(configPlan.getUserAutoRemarkId() != null ){
            //sysPluginMapper.deleteById(configPlan.getUserAutoRemarkId());
            idList.add(configPlan.getUserAutoRemarkId());
        }
        //删除提现插件id
        if(configPlan.getUserTakeBalId() != null ){
            //sysPluginMapper.deleteById(configPlan.getUserTakeBalId());
            idList.add(configPlan.getUserTakeBalId());
        }
        //删除个人信息查询插件id
        if(configPlan.getUserInfoQueryId() != null ){
            //sysPluginMapper.deleteById(configPlan.getUserInfoQueryId());
            idList.add(configPlan.getUserInfoQueryId());
        }
        //删除用户签到插件id
        if(configPlan.getUserSigninId() != null ){
            //sysPluginMapper.deleteById(configPlan.getUserSigninId());
            idList.add(configPlan.getUserSigninId());
        }
        //删除社群管理插件id
        if(configPlan.getCommunityId() != null ){
            //sysPluginMapper.deleteById(configPlan.getCommunityId());
            idList.add(configPlan.getCommunityId());
        }
        //删除订阅消息插件id
        if(configPlan.getSubscribeMsgId() != null ){
            //sysPluginMapper.deleteById(configPlan.getSubscribeMsgId());
            idList.add(configPlan.getSubscribeMsgId());
        }
        //删除其他设置插件id
        if(configPlan.getOtherId() != null ){
            //sysPluginMapper.deleteById(configPlan.getOtherId());
            idList.add(configPlan.getOtherId());
        }
        //删除导购插件id
        if(configPlan.getShoppingGuideId() != null ){
            //sysPluginMapper.deleteById(configPlan.getOtherId());
            idList.add(configPlan.getShoppingGuideId());
        }
        //删除微信公众号设置id
        if(configPlan.getWxpubSettingId() != null ){
            //sysPluginMapper.deleteById(configPlan.getOtherId());
            idList.add(configPlan.getWxpubSettingId());
        }
        //删除微信机器人关联公众号插件id
        if(configPlan.getWechatUnionWxpubId() != null ){
            //sysPluginMapper.deleteById(configPlan.getOtherId());
            idList.add(configPlan.getWechatUnionWxpubId());
        }
        //群功能设置插件id
        if(configPlan.getGroupBasesetId() != null ){
            //sysPluginMapper.deleteById(configPlan.getOtherId());
            idList.add(configPlan.getGroupBasesetId());
        }
        //群管功能插件id
        if(configPlan.getGroupManagerFuncId() != null ){
            //sysPluginMapper.deleteById(configPlan.getOtherId());
            idList.add(configPlan.getGroupManagerFuncId());
        }
        //群踢人设置插件id
        if(configPlan.getGroupKickId() != null ){
            //sysPluginMapper.deleteById(configPlan.getOtherId());
            idList.add(configPlan.getGroupKickId());
        }
        //群自动备注插件id
        if(configPlan.getGroupAutoRemarkId() != null ){
            //sysPluginMapper.deleteById(configPlan.getOtherId());
            idList.add(configPlan.getGroupAutoRemarkId());
        }

        //删除配置方案数据
        configPlanMapper.deleteById(configPlanIdDto.getId(), configPlanIdDto.getMerId());

        //删除此配置方案的微信群管理方案缓存
        try {
            if(configPlan.getDeviceType().equals(DeviceTypeGroupEnum.PRIVATE_WECHAT_GROUP.getKey())){ //个人微信群管理配置方案
                String redisKey_groupmanageplan = String.format(RedisCacheKeyEnum.WXQ_MANAGEPLAN.getKey(), configPlan.getId());
                redisTemplate.delete(redisKey_groupmanageplan);
            }else if(configPlan.getDeviceType().equals(DeviceTypeGroupEnum.WORK_WECHAT_GROUP.getKey())){//企业微信群管理配置方案
                String redisKey_groupmanageplan = String.format(RedisCacheKeyEnum.WXQ_WORK_MANAGEPLAN.getKey(), configPlan.getId());
                redisTemplate.delete(redisKey_groupmanageplan);
            }else if(configPlan.getDeviceType().equals(DeviceTypeGroupEnum.TIKTOK_GROUP.getKey())){//抖音群管理配置方案
                String redisKey_groupmanageplan = String.format(RedisCacheKeyEnum.TIKTOK_MANAGEPLAN.getKey(), configPlan.getId());
                redisTemplate.delete(redisKey_groupmanageplan);
            }
        }catch (Exception e){

        }

        //批量删除插件设置
        if(idList != null && idList.size() > 0){
            sysPluginMapper.batchDelete(idList);
            //删除redis缓存
            for (Long id : idList){
                //修改插件更新缓存，确保缓存和数据库一致
                redisTemplate.delete(String.format(RedisCacheKeyEnum.PLUGIN.getKey(), id));
            }
        }

        //删除指令表
        robotCmdMapper.deleteByConfigId(configPlanIdDto.getMerId(), configPlanIdDto.getId());

        //删除redis缓存中的指令
        redisTemplate.delete(String.format(RedisCacheKeyEnum.COMMAND_LIST.getKey(), configPlanIdDto.getId()));

    }

    /**
     * 复制配置方案
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param configPlanCopyDto
     * @return null
     */
    @Transactional
    public Long copyConfigPlan(ConfigPlanCopyDto configPlanCopyDto){
        //判断ID是否未空
        if(configPlanCopyDto.getId() == null || StringUtils.isBlank(configPlanCopyDto.getName())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //通过ID查询配置方案
        ConfigPlan configPlan = configPlanMapper.selectById(configPlanCopyDto.getId(), configPlanCopyDto.getMerId());
        if(configPlan == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "当前的配置方案不存在");
        }

        //验证名称重复
        ConfigPlan configPlan_name = configPlanMapper.selectByNameAndMerIdAndDeviceType(configPlanCopyDto.getName(), configPlan.getMerId(), configPlan.getDeviceType());
        if(configPlan_name != null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "名称重复");
        }


        Integer now = DateUtil.getNowTime();

        //复制插件件信息
        List<SysPlugin> sysPluginsList = new ArrayList<SysPlugin>();

        //淘宝插件ID
        if(configPlan.getTbId() != null ){
            //查询淘宝插件
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getTbId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加淘宝插件
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案的淘宝插件
                configPlan.setTbId(id);
            }
        }

        //京东插件id
        if(configPlan.getJdId()!= null ){
            //查询京东插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getJdId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加京东插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案的京东插件id
                configPlan.setJdId(id);
            }
        }

        //拼多多插件id
        if(configPlan.getPddId()!= null ){
            //查询拼多多插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getPddId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加拼多多插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案的拼多多插件id
                configPlan.setPddId(id);
            }
        }

        //唯品会插件id
        if(configPlan.getVphId()!= null ){
            //查询唯品会插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getVphId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加唯品会插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案的唯品会插件id
                configPlan.setVphId(id);
            }
        }

        //抖音插件id
        if(configPlan.getDyId()!= null ){
            //查询唯品会插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getDyId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加唯品会插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案的唯品会插件id
                configPlan.setDyId(id);
            }
        }

        //本地生活插件id
        if(configPlan.getLocalLiveId()!= null ){
            //查询本地生活插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getLocalLiveId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加本地生活插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案的本地生活插件id
                configPlan.setLocalLiveId(id);

                //本地生活指令
                //robotCmdService.addRobotCmdForConfigPlan(configPlan.getMerId(), configPlan.getId(), PluginKeyEnum.LOCAL_LIVE.getValue(), sysPlugin.getData());

            }
        }

        //拉群规则
        if(configPlan.getPullWxgroupRuleId() != null ){
            //查询微信好友添加插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getPullWxgroupRuleId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加微信好友添加插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案的微信好友添加插件id
                configPlan.setPullWxgroupRuleId(id);
            }
        }

        //微信好友添加插件id
        if(configPlan.getWxUserAddId()!= null ){
            //查询微信好友添加插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getWxUserAddId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加微信好友添加插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案的微信好友添加插件id
                configPlan.setWxUserAddId(id);
            }
        }

        //推广裂变插件id
        if(configPlan.getUserExpandFissionId()!= null ){
            //查询推广裂变插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserExpandFissionId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加推广裂变插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案的推广裂变插件id
                configPlan.setUserExpandFissionId(id);
            }
        }

        //提现插件id
        if(configPlan.getUserTakeBalId()!= null ){
            //查询提现插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserTakeBalId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加提现插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案中提现插件id
                configPlan.setUserTakeBalId(id);

                //保存提现指令
                //robotCmdService.addRobotCmdForConfigPlan(configPlan.getMerId(), configPlan.getId(), PluginKeyEnum.USER_TAKE_BAL.getValue(), sysPlugin.getData());

            }
        }

        //好友引导插件id
        if(configPlan.getUserGuideId()!= null ){
            //好友引导插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserGuideId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加好友引导插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案中好友引导插件id
                configPlan.setUserGuideId(id);
            }
        }

        //自动备注插件id
        if(configPlan.getUserAutoRemarkId()!= null ){
            //自动备注插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserAutoRemarkId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加自动备注插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案中自动备注插件id
                configPlan.setUserAutoRemarkId(id);
            }
        }

        //订阅消息插件id
        if(configPlan.getSubscribeMsgId()!= null ){
            //订阅消息插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getSubscribeMsgId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加订阅消息插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案中订阅消息插件id
                configPlan.setSubscribeMsgId(id);

                //保存订阅指令
                //robotCmdService.addRobotCmdForConfigPlan(configPlan.getMerId(), configPlan.getId(), PluginKeyEnum.SUBSCRIBE_MSG.getValue(), sysPlugin.getData());
            }
        }

        //个人信息查询插件id
        if(configPlan.getUserInfoQueryId()!= null ){
            //订阅消息插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserInfoQueryId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加个人信息查询插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案中个人信息查询插件id
                configPlan.setUserInfoQueryId(id);

                //保存个人信息指令
                //robotCmdService.addRobotCmdForConfigPlan(configPlan.getMerId(), configPlan.getId(), PluginKeyEnum.USER_INFO_QUERY.getValue(), sysPlugin.getData());

            }
        }

        //用户签到插件id
        if(configPlan.getUserSigninId()!= null ){
            //用户签到插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserSigninId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加用户签到插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案中用户签到插件id
                configPlan.setUserSigninId(id);

                //保存用户签到指令
                //robotCmdService.addRobotCmdForConfigPlan(configPlan.getMerId(), configPlan.getId(), PluginKeyEnum.USER_SIGNIN.getValue(), sysPlugin.getData());

            }
        }

        //社群管理插件id
        if(configPlan.getCommunityId()!= null ){
            //社群管理插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getCommunityId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加社群管理插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案中社群管理插件id
                configPlan.setCommunityId(id);

                //保存社群指令
                //robotCmdService.addRobotCmdForConfigPlan(configPlan.getMerId(), configPlan.getId(), PluginKeyEnum.COMMUNITY.getValue(), sysPlugin.getData());

            }
        }

        //其他设置插件id
        if(configPlan.getOtherId()!= null ){
            //其他设置插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getOtherId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加其他设置插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案中其他设置插件id
                configPlan.setOtherId(id);
            }
        }

        //导购插件
        if(configPlan.getShoppingGuideId() != null ){
            //其他设置插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getShoppingGuideId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加其他设置插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案中其他设置插件id
                configPlan.setShoppingGuideId(id);
            }
        }

        //微信公众号设置id
        if(configPlan.getWxpubSettingId() != null ){
            //其他设置插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getWxpubSettingId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加其他设置插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案中其他设置插件id
                configPlan.setWxpubSettingId(id);
            }
        }

        //微信机器人关联公众号插件id
        if(configPlan.getWechatUnionWxpubId() != null ){
            //其他设置插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getWechatUnionWxpubId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加其他设置插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案中其他设置插件id
                configPlan.setWechatUnionWxpubId(id);
            }
        }

        //复制大促插件
        if(configPlan.getBigPromotionId() != null ){
            //其他设置插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getBigPromotionId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                try {
                    JSONObject jsonObject = JSONObject.parseObject(sysPlugin.getData());
                    if(jsonObject != null){
                        //清理淘宝联盟
                        JSONObject dc_tb_data = jsonObject.getJSONObject("dc_tb");
                        if(dc_tb_data != null){
                            dc_tb_data.put("session","");
                            dc_tb_data.put("pid","");
                            jsonObject.put("dc_tb", dc_tb_data);
                        }
                        //清理京东联盟
                        JSONObject dc_jd_data = jsonObject.getJSONObject("dc_jd");
                        if(dc_jd_data != null){
                            dc_jd_data.put("unionid","");
                            jsonObject.put("dc_jd", dc_jd_data);
                        }
                        sysPlugin.setData(jsonObject.toJSONString());
                    }
                }catch (Exception e){

                }
                //新加其他设置插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案中大促插件id
                configPlan.setBigPromotionId(id);
            }
        }

        //复制客户端设置插件
        if(configPlan.getClientSetId() != null ){
            //其他设置插件id
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getClientSetId(), configPlanCopyDto.getMerId());
            if(sysPlugin != null){
                Long id = IdWorker.getId();
                sysPlugin.setId(id);
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                //新加其他设置插件id
                //sysPluginMapper.insert(sysPlugin);
                sysPluginsList.add(sysPlugin);
                //修改配置方案中其他设置插件id
                configPlan.setClientSetId(id);
            }
        }


        //批量插入插件
        if(sysPluginsList != null & sysPluginsList.size() > 0){
            sysPluginMapper.batchAdd(sysPluginsList);
            for(SysPlugin sysPlugin : sysPluginsList){
                //修改插件更新缓存，确保缓存和数据库一致
                redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.PLUGIN.getKey(), sysPlugin.getId()) , sysPlugin.getData(), 5, TimeUnit.DAYS);
            }
        }

        //添加新的配置方案
        //生成新的配置ID
        Long configPlanId_new = IdWorker.getId();
        configPlan.setId(configPlanId_new);
        configPlan.setName(configPlanCopyDto.getName());
        configPlan.setCreateTime(now);
        configPlan.setUpdateTime(now);
        configPlan.setIsDefault(0); //不默认
        //清空会员类型组和分佣
//        configPlan.setUserTypeGroupId(null);
//        configPlan.setTbCommissionPlanId(null);
//        configPlan.setJdCommissionPlanId(null);
//        configPlan.setPddCommissionPlanId(null);
//        configPlan.setVphCommissionPlanId(null);
//        configPlan.setLocalLiveCommissionPlanId(null);
//        configPlan.setDyCommissionPlanId(null);

        configPlanMapper.insert(configPlan);

        //查出旧指令列表
        List<RobotCmd> robotCmdList = robotCmdMapper.selectByConfigId(configPlanCopyDto.getMerId(), configPlanCopyDto.getId());
        if(robotCmdList != null && robotCmdList.size() > 0){
            for (RobotCmd robotCmd : robotCmdList){
                robotCmd.setId(IdWorker.getId()); //更新旧指令ID
                robotCmd.setConfigId(configPlanId_new);//更新旧指令配置方案
                robotCmd.setUpdateTime(now);
                robotCmd.setCreateTime(now);
            }

            //批量插入指令表数据库
            robotCmdMapper.batchAdd(robotCmdList);

            //更新新的指令缓存redis
            String data = Tools.getStrEmpty(JSONObject.toJSONString(robotCmdList));
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.COMMAND_LIST.getKey(), configPlanId_new), data);

        }

        return configPlanId_new;

    }

    /**
     * 查询插件
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param configPlanPluginIdDto
     * @return null
     */
    public SysPluginVo findSysPluginInfo(ConfigPlanPluginIdDto configPlanPluginIdDto){

        if(configPlanPluginIdDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        SysPlugin sysPlugin = sysPluginMapper.selectById(configPlanPluginIdDto.getId(), configPlanPluginIdDto.getMerId());
        if(sysPlugin == null){
            sysPlugin = new SysPlugin();
        }

        //提现插件，需要脱敏处理
        if("user_take_bal".equals(sysPlugin.getPlugName())){
            JSONObject jsonObject = JSONObject.parseObject(sysPlugin.getData());
            if(jsonObject != null){
                String zf_app_id = Tools.getStr(jsonObject.getString("zf_app_id"));
                String zf_app_key = Tools.getStr(jsonObject.getString("zf_app_key"));
                //String wxpay_zf_app_id = Tools.getStr(jsonObject.getString("wxpay_zf_app_id"));     //20230307舍弃
                //String wxpay_zf_app_key = Tools.getStr(jsonObject.getString("wxpay_zf_app_key"));   //20230307舍弃
                String alipay_zf_app_id = Tools.getStr(jsonObject.getString("alipay_zf_app_id"));
                String alipay_zf_app_key = Tools.getStr(jsonObject.getString("alipay_zf_app_key"));
                String wx_redpacket_pay_password = Tools.getStr(jsonObject.getString("wx_redpacket_pay_password"));
                //脱敏之后保存
                jsonObject.put("zf_app_id", DesensitizeUtil.around(zf_app_id, 4, 4));
                jsonObject.put("zf_app_key", DesensitizeUtil.around(zf_app_key, 4, 4));
                //jsonObject.put("wxpay_zf_app_id", DesensitizeUtil.around(wxpay_zf_app_id, 4, 4));
                //jsonObject.put("wxpay_zf_app_key", DesensitizeUtil.around(wxpay_zf_app_key, 4, 4));
                jsonObject.put("alipay_zf_app_id", DesensitizeUtil.around(alipay_zf_app_id, 4, 4));
                jsonObject.put("alipay_zf_app_key", DesensitizeUtil.around(alipay_zf_app_key, 4, 4));
                jsonObject.put("wx_redpacket_pay_password", DesensitizeUtil.around(wx_redpacket_pay_password, 1, 1));

                sysPlugin.setData(jsonObject.toJSONString());
            }
        }else if("tb".equals(sysPlugin.getPlugName())){//淘宝插件-APP的淘宝插件，针对淘礼金需要脱敏

            //判断是否需要脱敏
            String cmstype_amoy_gold_app_secret_verified =  (String)redisTemplate.opsForValue().get(String.format(Const.SmsType.CMSTYPE_AMOY_GOLD_APP_SECRET, sysPlugin.getMerId()));
            if(StringUtils.isBlank(cmstype_amoy_gold_app_secret_verified)){
                JSONObject jsonObject = JSONObject.parseObject(sysPlugin.getData());
                if(jsonObject != null){
                    //淘礼金appSecret
                    String amoy_gold_app_secret = Tools.getStr(jsonObject.getString("amoy_gold_app_secret"));
                    //脱敏之后返回
                    jsonObject.put("amoy_gold_app_secret", DesensitizeUtil.around(amoy_gold_app_secret, 4, 4));
                    sysPlugin.setData(jsonObject.toJSONString());
                }
            }
        }
        //返回给页面的对象
        SysPluginVo sysPluginVo = new SysPluginVo();
        BeanUtils.copyProperties(sysPlugin, sysPluginVo);
        return  sysPluginVo;
    }

    /**
     * 修改插件信息
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param configPlanPluginUpdateDto
     * @return null
     */
    @Transactional
    public Long updateSysPlugin(ConfigPlanPluginUpdateDto configPlanPluginUpdateDto){

        Merchant merchant = merchantMapper.selectById(configPlanPluginUpdateDto.getMerId());
        if(merchant == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "当前运营商不存在");
        }

        if(configPlanPluginUpdateDto.getConfigPlanID() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择配置方案");
        }

        if(StringUtils.isBlank(configPlanPluginUpdateDto.getPlugName()) || StringUtils.isBlank(configPlanPluginUpdateDto.getData())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //页面传过来的是驼峰型，末尾是Id的后缀去掉末尾Id
        String plugName_hump = configPlanPluginUpdateDto.getPlugName().replaceAll("Id","");
        //驼峰型转成下划线型
        String plugName = Tools.humpToLine(plugName_hump);

        //如果是提现插件，则先查询出该插件
        if("user_take_bal".equals(plugName)){
            //微信红包旧账房appId
            String zf_app_id_old = "";
            //微信红包旧账房appKey
            String zf_app_key_old = "";
            //支付宝旧账房appId
            String alipay_zf_app_id_old = "";
            //支付宝旧账房appKey
            String alipay_zf_app_key_old = "";
            //微信红包支付密码
            String wx_redpacket_pay_password_old = "";
            //如果旧插件id存在
            if(configPlanPluginUpdateDto.getId() != null){
                SysPlugin sysPlugin_old = sysPluginMapper.selectById(configPlanPluginUpdateDto.getId(), configPlanPluginUpdateDto.getMerId());
                if(sysPlugin_old != null){
                    JSONObject jsonObject_old = JSONObject.parseObject(sysPlugin_old.getData());
                    if(jsonObject_old != null){
                        zf_app_id_old = jsonObject_old.getString("zf_app_id");
                        zf_app_key_old = jsonObject_old.getString("zf_app_key");
                        alipay_zf_app_id_old = jsonObject_old.getString("alipay_zf_app_id");
                        alipay_zf_app_key_old = jsonObject_old.getString("alipay_zf_app_key");
                        wx_redpacket_pay_password_old = jsonObject_old.getString("wx_redpacket_pay_password");
                    }
                }
            }

            JSONObject jsonObject_new = JSONObject.parseObject(configPlanPluginUpdateDto.getData());
            if(jsonObject_new != null){
                //微信红包账房appId
                String zf_app_id_new = Tools.getStr(jsonObject_new.getString("zf_app_id"));
                //微信红包账房appKey
                String zf_app_key_new = Tools.getStr(jsonObject_new.getString("zf_app_key"));
                //支付宝账房appId
                String alipay_zf_app_id_new = Tools.getStr(jsonObject_new.getString("alipay_zf_app_id"));
                //支付宝账房appKey
                String alipay_zf_app_key_new = Tools.getStr(jsonObject_new.getString("alipay_zf_app_key"));
                //微信红包支付密码
                String wx_redpacket_pay_password_new = Tools.getStr(jsonObject_new.getString("wx_redpacket_pay_password"));

                //如果包含星星，则不修改
                if(zf_app_id_new.contains("*")){
                    jsonObject_new.put("zf_app_id", zf_app_id_old);
                    zf_app_id_new = zf_app_id_old;
                }
                if(zf_app_key_new.contains("*")){
                    jsonObject_new.put("zf_app_key", zf_app_key_old);
                    zf_app_key_new = zf_app_key_old;
                }
                if(alipay_zf_app_id_new.contains("*")){
                    jsonObject_new.put("alipay_zf_app_id", alipay_zf_app_id_old);
                    alipay_zf_app_id_new = alipay_zf_app_id_old;
                }
                if(alipay_zf_app_key_new.contains("*")){
                    jsonObject_new.put("alipay_zf_app_key", alipay_zf_app_key_old);
                    alipay_zf_app_key_new = alipay_zf_app_key_old;
                }
                if(wx_redpacket_pay_password_new.contains("*")){
                    jsonObject_new.put("wx_redpacket_pay_password", wx_redpacket_pay_password_old);
                }

                //验证微信转账账房appid和appkey
                //Integer wechat_pay_switch = Tools.getInteger(jsonObject_new.getInteger("wechat_pay_switch")); //微信自动提现开关
                //if(wechat_pay_switch.intValue() == 1){ //开启才验证,2024-04-28修改为不判断开关
                    if(StringUtils.isNotBlank(zf_app_id_new) && StringUtils.isNotBlank(zf_app_key_new)){
                        CashierAppCheckDto cashierAppCheckDto_redpacket = new CashierAppCheckDto();
                        cashierAppCheckDto_redpacket.setAppid(zf_app_id_new);
                        cashierAppCheckDto_redpacket.setAppkey(zf_app_key_new);
                        cashierAppCheckDto_redpacket.setMobile(merchant.getMobile());
                        UzaiRespVo<Boolean> uzaiRespVo_redpacket = userTakeBalFeignService.cashierAppCheck(cashierAppCheckDto_redpacket);
                        logger.info("--验证微信自动提现账房appid和appkey正确性--para={}, result={}", JSONObject.toJSONString(cashierAppCheckDto_redpacket), JSONObject.toJSONString(uzaiRespVo_redpacket));
                        if(uzaiRespVo_redpacket == null || uzaiRespVo_redpacket.getCode() != 200){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, StringUtils.isNotBlank(uzaiRespVo_redpacket.getMsg())?uzaiRespVo_redpacket.getMsg() : "支付宝自动提现设置appid和appkey填写不正确");
                        }
                    }
                //}

                //验证支付宝账房appid和appkey
                //Integer alipay_switch = Tools.getInteger(jsonObject_new.getInteger("alipay_switch")); //支付宝自动提现开关
                //if(alipay_switch.intValue() == 1){ //开启才验证
                    if(StringUtils.isNotBlank(alipay_zf_app_id_new) && StringUtils.isNotBlank(alipay_zf_app_key_new)){
                        CashierAppCheckDto cashierAppCheckDto_alipay = new CashierAppCheckDto();
                        cashierAppCheckDto_alipay.setAppid(alipay_zf_app_id_new);
                        cashierAppCheckDto_alipay.setAppkey(alipay_zf_app_key_new);
                        cashierAppCheckDto_alipay.setMobile(merchant.getMobile());
                        UzaiRespVo<Boolean> uzaiRespVo_alipay = userTakeBalFeignService.cashierAppCheck(cashierAppCheckDto_alipay);
                        logger.info("--验证支付宝自动提现账房appid和appkey正确性--para={}, result={}", JSONObject.toJSONString(cashierAppCheckDto_alipay), JSONObject.toJSONString(uzaiRespVo_alipay));
                        if(uzaiRespVo_alipay == null || uzaiRespVo_alipay.getCode() != 200 ){
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, StringUtils.isNotBlank(uzaiRespVo_alipay.getMsg())?uzaiRespVo_alipay.getMsg() : "支付宝自动提现设置appid和appkey填写不正确");
                        }
                    }
                //}

                configPlanPluginUpdateDto.setData(jsonObject_new.toJSONString());
            }
        }else if("tb".equals(plugName)) {//淘宝插件-APP的淘宝插件，针对淘礼金需要脱敏
            //APP淘礼金appSecret
            String amoy_gold_app_secret_old = "";
            //如果旧插件id存在
            if(configPlanPluginUpdateDto.getId() != null){
                SysPlugin sysPlugin_old = sysPluginMapper.selectById(configPlanPluginUpdateDto.getId(), configPlanPluginUpdateDto.getMerId());
                if(sysPlugin_old != null){
                    JSONObject jsonObject_old = JSONObject.parseObject(sysPlugin_old.getData());
                    if(jsonObject_old != null){
                        amoy_gold_app_secret_old = jsonObject_old.getString("amoy_gold_app_secret");
                    }
                }
            }

            JSONObject jsonObject_new = JSONObject.parseObject(configPlanPluginUpdateDto.getData());
            if(jsonObject_new != null){
                //APP淘礼金appSecret
                String amoy_gold_app_secret_new = Tools.getStr(jsonObject_new.getString("amoy_gold_app_secret"));
                //如果包含星星，则不修改
                if(amoy_gold_app_secret_new.contains("*")){
                    jsonObject_new.put("amoy_gold_app_secret", amoy_gold_app_secret_old);
                }
                configPlanPluginUpdateDto.setData(jsonObject_new.toJSONString());
            }
        }

        //查询配置方案
        ConfigPlan configPlan = configPlanMapper.selectById(configPlanPluginUpdateDto.getConfigPlanID(), configPlanPluginUpdateDto.getMerId());
        if(configPlan == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该配置方案不存在");
        }

        //插件ID存在，则修改
        if(configPlanPluginUpdateDto.getId() != null){
            int count = configPlanMapper.selectCountByPluginName(plugName+"_id", configPlanPluginUpdateDto.getId());
            if(count == 1){//自己一个人使用，先删除
                //清除插件
                sysPluginMapper.deleteById(configPlanPluginUpdateDto.getId(), configPlanPluginUpdateDto.getMerId());
            }
            //重新添加
            Integer now = DateUtil.getNowTime();
            //生成新的插件id
            Long id = IdWorker.getId(); //生成新的插件id
            //返回到页面用
            configPlanPluginUpdateDto.setId(id);
            SysPlugin sysPlugin = new SysPlugin();
            sysPlugin.setId(id);
            sysPlugin.setMerId(configPlanPluginUpdateDto.getMerId());
            sysPlugin.setPlugName(plugName);
            sysPlugin.setData(configPlanPluginUpdateDto.getData());
            sysPlugin.setCreateTime(now);
            sysPlugin.setUpdateTime(now);
            sysPluginMapper.insert(sysPlugin);

            //修改插件更新缓存，确保缓存和数据库一致
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.PLUGIN.getKey(), sysPlugin.getId()) , sysPlugin.getData(), 5,TimeUnit.DAYS);

            //反射配置方案类，设置对应的插件ID
            Class cls = configPlan.getClass();
            Field field = null;
            try {
                field = cls.getDeclaredField(configPlanPluginUpdateDto.getPlugName());
                field.setAccessible(true);//设置允许访问
                field.set(configPlan, id);
                //修改配置方案
                configPlanMapper.update(configPlan);
            } catch (Exception e) {
            }

        }else{//插件ID不存在，则新增
            Integer now = DateUtil.getNowTime();
            Long id = IdWorker.getId();
            //返回到页面用
            configPlanPluginUpdateDto.setId(id);
            SysPlugin sysPlugin = new SysPlugin();
            sysPlugin.setId(id);
            sysPlugin.setMerId(configPlanPluginUpdateDto.getMerId());
            sysPlugin.setPlugName(plugName);
            sysPlugin.setData(configPlanPluginUpdateDto.getData());
            sysPlugin.setCreateTime(now);
            sysPlugin.setUpdateTime(now);
            sysPluginMapper.insert(sysPlugin);

            //修改插件更新缓存，确保缓存和数据库一致
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.PLUGIN.getKey(), sysPlugin.getId()) , sysPlugin.getData(), 5,TimeUnit.DAYS);

            //反射配置方案类，设置对应的插件ID
            Class cls = configPlan.getClass();
            Field field = null;
            try {
                field = cls.getDeclaredField(configPlanPluginUpdateDto.getPlugName());
                field.setAccessible(true);//设置允许访问
                field.set(configPlan, id);
                //修改配置方案
                configPlanMapper.update(configPlan);
            } catch (Exception e) {
            }
        }

        //如果是其他插件,需要将信息添加到Redis当中得 设备消息回复配置信息
        if("other".equals(plugName)){
            //查询该所有使用过该配置得机器人
            DeviceQuery deviceQuery = new DeviceQuery();
            deviceQuery.setMerId(configPlan.getMerId());
            deviceQuery.setDeviceType(configPlan.getDeviceType());
            deviceQuery.setConfigId(configPlan.getId());
            List<DeviceInfoVo> deviceList = deviceService.findDeviceList(deviceQuery);
            if(deviceList != null && deviceList.size() > 0){
               for (DeviceInfoVo deviceInfoVo : deviceList){
                   //保存其他设置缓存
                   redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_MSG_CONFIG.getKey(), deviceInfoVo.getId()) , configPlanPluginUpdateDto.getData());
                   //调用微服务通知移动端APP更新
                   try {
                       //微信好友添加插件
                       JSONObject data = JSONObject.parseObject(configPlanPluginUpdateDto.getData());
                       //企业微信通过验证再添加好友开关（0关，1开）, 默认关闭
                       Integer autoPassPcLogin = 0;//
                       if(data != null){
                           autoPassPcLogin = Tools.getInteger(data.getInteger("auto_pass_pc_login"));//自动允许pc登录开关（0关，1开）,默认关闭. 2022-1207新增
                       }
                       //发送微服务，通知终端
                       MsgDto<AndroidSetConfigDto> msgDto = new MsgDto<>();
                       AndroidSetConfigDto androidSetConfigDto = new AndroidSetConfigDto();
                       msgDto.setContent(androidSetConfigDto);
                       msgDto.setId(IdWorker.getId());
                       msgDto.setDeviceType(deviceInfoVo.getRecvmsgType());
                       msgDto.setDeviceUniqueId(deviceInfoVo.getId());
                       msgDto.setMerId(deviceInfoVo.getMerId());
                       msgDto.setMsgType(MessageFuncEnum.PUSH_ANDROID_SETCONFIG.getValue());
                       //封装参数对象
                       androidSetConfigDto.setWxid(deviceInfoVo.getDeviceId());
                       androidSetConfigDto.setAutoExLogin(autoPassPcLogin);
                       UzaiRespVo<Object> uzaiRespVo =  uzaiImClientFeignService.androidSetConfigPush(msgDto);
                       logger.info("---调用安卓版配置推送接口接口----para={},result={}", JSONObject.toJSONString(msgDto), JSONObject.toJSONString(uzaiRespVo));
                   }catch(Exception e) {}
               }
            }
        }

        //如果是微信好友添加,需要将企业微信通过验证再添加好友开关 添加到Redis当中得 设备消息回复配置信息
        if("wx_user_add".equals(plugName)){
            //微信好友添加插件
            JSONObject data = JSONObject.parseObject(configPlanPluginUpdateDto.getData());
            //企业微信通过验证再添加好友开关（0关，1开）, 默认关闭
            Integer qwechat_pass = 0;//
            if(data != null){
                qwechat_pass = Tools.getInteger(data.getInteger("qwechat_pass"));
            }

            //查询该所有使用过该配置得机器人
            DeviceQuery deviceQuery = new DeviceQuery();
            deviceQuery.setMerId(configPlan.getMerId());
            deviceQuery.setDeviceType(configPlan.getDeviceType());
            deviceQuery.setConfigId(configPlan.getId());
            List<DeviceInfoVo> deviceList = deviceService.findDeviceList(deviceQuery);
            if(deviceList != null && deviceList.size() > 0){
                for (DeviceInfoVo deviceInfoVo : deviceList){
                    redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.QWECHAT_PASS.getKey(), deviceInfoVo.getId()), qwechat_pass);
                }
            }
        }

        //大促插件需要推送给客户端
        if("big_promotion".equals(plugName)){

            //查询该配置方案使用的机器人
            DeviceWechatInfoQuery query = new DeviceWechatInfoQuery();
            query.setMerId(configPlanPluginUpdateDto.getMerId());
            query.setConfigId(configPlanPluginUpdateDto.getConfigPlanID());
            List<DeviceWechatInfo> deviceWechatInfoList = deviceWechatInfoMapper.findByList(query);
            if(deviceWechatInfoList != null && deviceWechatInfoList.size() > 0){
                for (DeviceWechatInfo deviceWechatInfo : deviceWechatInfoList) {
                    //推送给客户端
                    // TODO: 2021/9/4  发送消息
                    //发送MQ消息
                    MsgDto<BigPromotionDto> msgDto = new MsgDto<>();
                    BigPromotionDto  bigPromotionDto = new BigPromotionDto();
                    msgDto.setContent(bigPromotionDto);
                    msgDto.setId(IdWorker.getId());
                    msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
                    msgDto.setDeviceUniqueId(deviceWechatInfo.getId());
                    msgDto.setMerId(deviceWechatInfo.getMerId());
                    msgDto.setMsgType(MessageFuncEnum.PUSH_CLIENT_SETTING.getValue());
                    bigPromotionDto.setSetType(1); //
                    bigPromotionDto.setData(configPlanPluginUpdateDto.getData());
                    noticeMsgPushProducerService.pushBigPromotion(msgDto);
                }
            }
        }

        //客户端设计，需要推送给客户端
        if("client_set".equals(plugName) ){
            //查询该配置方案使用的机器人
            DeviceWechatInfoQuery query = new DeviceWechatInfoQuery();
            query.setMerId(configPlanPluginUpdateDto.getMerId());
            query.setConfigId(configPlanPluginUpdateDto.getConfigPlanID());
            List<DeviceWechatInfo> deviceWechatInfoList = deviceWechatInfoMapper.findByList(query);
            if(deviceWechatInfoList != null && deviceWechatInfoList.size() > 0){
                for (DeviceWechatInfo deviceWechatInfo : deviceWechatInfoList) {
                    //推送给客户端
                    // TODO: 2021/9/4  发送消息
                    //发送MQ消息
                    MsgDto<ClientSetDto> msgDto = new MsgDto<>();
                    ClientSetDto  clientSetDto = new ClientSetDto();
                    msgDto.setContent(clientSetDto);
                    msgDto.setId(IdWorker.getId());
                    msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
                    msgDto.setDeviceUniqueId(deviceWechatInfo.getId());
                    msgDto.setMerId(deviceWechatInfo.getMerId());
                    msgDto.setMsgType(MessageFuncEnum.PUSH_CLIENT_SETTING.getValue());
                    clientSetDto.setSetType(2);

                    //客户端设置对象（将点赞屏蔽朋友圈会员id列表封装成会员wxid列表）
                    JSONObject object = JSONObject.parseObject(configPlanPluginUpdateDto.getData());
                    if(object != null){
                        List<String> pyq_like_exclude = JSONObject.parseArray(object.getString("pyq_like_exclude"), String.class);
                        if(pyq_like_exclude != null && pyq_like_exclude.size() > 0){
                            //封装wxid字段
                            List<String> wxidList = new ArrayList<>();
                            for (String userId : pyq_like_exclude) {
                                if(StringUtils.isNumeric(userId)){//如果是纯数字，则表示会员id,则需要转化成
                                    WechatUser wechatUser =  wechatUserMapper.selectById(Long.valueOf(userId), deviceWechatInfo.getMerId());
                                    if(wechatUser != null){
                                        wxidList.add(wechatUser.getBizUserId());
                                    }
                                }else{
                                    wxidList.add(userId);
                                }
                            }
                            if(wxidList != null && wxidList.size() > 0){
                                object.put("pyq_like_exclude", JSONObject.toJSONString(wxidList));
                            }
                        }
                    }else{
                        object = new JSONObject();
                    }
                    clientSetDto.setData(object.toJSONString());
                    noticeMsgPushProducerService.pushClientSet(msgDto);
                }
            }
        }

        //保存微信群基础设置
        if("group_baseset".equals(plugName)){
            //个人微信群设置
            if(configPlan.getDeviceType().equals(DeviceTypeGroupEnum.PRIVATE_WECHAT_GROUP.getKey())){
                String redisKey_groupmanageplan = String.format(RedisCacheKeyEnum.WXQ_MANAGEPLAN.getKey(), configPlan.getId());
                redisTemplate.opsForValue().set(redisKey_groupmanageplan, configPlanPluginUpdateDto.getData());
            }else if(configPlan.getDeviceType().equals(DeviceTypeGroupEnum.WORK_WECHAT_GROUP.getKey())){//企业微信群设置
                String redisKey_groupmanageplan = String.format(RedisCacheKeyEnum.WXQ_WORK_MANAGEPLAN.getKey(), configPlan.getId());
                redisTemplate.opsForValue().set(redisKey_groupmanageplan, configPlanPluginUpdateDto.getData());
            }else if(configPlan.getDeviceType().equals(DeviceTypeGroupEnum.TIKTOK_GROUP.getKey())){//抖音群设置
                String redisKey_groupmanageplan = String.format(RedisCacheKeyEnum.TIKTOK_MANAGEPLAN.getKey(), configPlan.getId());
                redisTemplate.opsForValue().set(redisKey_groupmanageplan, configPlanPluginUpdateDto.getData());
            }
        }

        //保存微信群群管功能设置
        if("group_manager_func".equals(plugName)){
            //个人微信群设置
            if(configPlan.getDeviceType().equals(DeviceTypeGroupEnum.WORK_WECHAT_GROUP.getKey())){//企业微信群设置
                JSONObject data = JSONObject.parseObject(configPlanPluginUpdateDto.getData());
                //企业微信群邀请确认（0关，1开）, 默认关闭
                Integer groupInviteConfrom = 0;//
//                if(data != null){
//                    groupInviteConfrom = Tools.getInteger(data.getInteger("groupInviteConfrom"));
//                }
//                //调用微服务发送接口
//                MsgDto<WorkWxSetGroupInviteConfirm> msgDto = new MsgDto<>();
//                WorkWxSetGroupInviteConfirm  workWxSetGroupInviteConfirm = new WorkWxSetGroupInviteConfirm();
//                workWxSetGroupInviteConfirm.setGroupId(null);
//                workWxSetGroupInviteConfirm.setStatus(groupInviteConfrom);
//                msgDto.setContent(workWxSetGroupInviteConfirm);
//                msgDto.setId(IdWorker.getId());
//                msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
//                msgDto.setDeviceUniqueId(deviceWechatInfo.getId());
//                msgDto.setMerId(deviceWechatInfo.getMerId());
//                msgDto.setMsgType(MessageFuncEnum.PUSH_CLIENT_SETTING.getValue());
//                //调用微服务
//                UzaiRespVo<Object> uzaiRespVo = uzaiImClientFeignService.workwxSetgroupInviteconfirm(msgDto);
//                logger.info("--调用企业微信邀请入群接口--para={},result={}",JSONObject.toJSONString(msgDto), JSONObject.toJSONString(uzaiRespVo));
//                if(uzaiRespVo != null && uzaiRespVo.getCode() != 200){
//                    throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
//                }
            }
        }

        if(configPlanPluginUpdateDto.getConfigPlanID() != null){
            //修改指令
            robotCmdService.addRobotCmdForConfigPlan(configPlanPluginUpdateDto.getMerId(), configPlanPluginUpdateDto.getConfigPlanID(), plugName, configPlanPluginUpdateDto.getData());
            //更新指令redis缓存
            List<RobotCmd> robotCmdList = robotCmdMapper.selectByConfigId(configPlanPluginUpdateDto.getMerId(), configPlanPluginUpdateDto.getConfigPlanID());
            String data = Tools.getStrEmpty(JSONObject.toJSONString(robotCmdList));
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.COMMAND_LIST.getKey(), configPlanPluginUpdateDto.getConfigPlanID()), data);
        }

        return configPlanPluginUpdateDto.getId();

    }

    /**
     * 批量修改插件
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param configPlanPluginBatchUpdateDto
     * @return null
     */
    @Transactional
    public void batchUpdateSysPlugin(ConfigPlanPluginBatchUpdateDto configPlanPluginBatchUpdateDto){

        List<Long> configPlanIdList = configPlanPluginBatchUpdateDto.getConfigPlanIDList();

        if(configPlanIdList == null || configPlanIdList.size() == 0 || StringUtils.isBlank(configPlanPluginBatchUpdateDto.getPlugName()) || StringUtils.isBlank(configPlanPluginBatchUpdateDto.getData())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        JSONObject dataJSONObject_para = JSONObject.parseObject(configPlanPluginBatchUpdateDto.getData());
        if(dataJSONObject_para == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        Set<String> keySet_para =  dataJSONObject_para.keySet();
        if(keySet_para == null || keySet_para.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //页面传过来的是驼峰型，末尾是Id的后缀去掉末尾Id
        String plugName_hump = configPlanPluginBatchUpdateDto.getPlugName().replaceAll("Id","");
        //驼峰型转成下划线型
        String plugName = Tools.humpToLine(plugName_hump);

        //更新事件
        Integer now = DateUtil.getNowTime();

        for (Long configPlanId : configPlanIdList){
            //查询配置方案
            ConfigPlan configPlan = configPlanMapper.selectById(configPlanId, configPlanPluginBatchUpdateDto.getMerId());
            if(configPlan == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该配置方案不存在");
            }

            //通过反射机制，获取对应的插件id
            Long  pluginId = (Long)Tools.getValueByReflex(configPlan, configPlanPluginBatchUpdateDto.getPlugName());
            //临时保存最新的插件数据，修改指令时使用。
            String data_other = "";

            if(pluginId != null){ //插件存在，
                SysPlugin sysPlugin = sysPluginMapper.selectById(pluginId, configPlan.getMerId());
                if(sysPlugin != null){ //插件表中查询到该插件
                    //则修改该插件内容
                    JSONObject jsonObject_value = JSONObject.parseObject(sysPlugin.getData());
                    if(jsonObject_value ==  null){
                        jsonObject_value = new JSONObject();
                    }
                    //替换
//                    for (String key_para : keySet_para) {
//                        Object value_vara = dataJSONObject_para.get(key_para);
//                        jsonObject_value.put(key_para, value_vara);
//                    }
                    //修改2023-10-26, 依次递归子对象替换
                    replace(jsonObject_value, dataJSONObject_para);

                    sysPlugin.setData(jsonObject_value.toJSONString());
                    sysPlugin.setUpdateTime(now);
                    sysPluginMapper.update(sysPlugin);

                    //修改插件更新缓存，确保缓存和数据库一致
                    redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.PLUGIN.getKey(), sysPlugin.getId()) , sysPlugin.getData(), 5,TimeUnit.DAYS);

                    //其他插件内容
                    data_other = sysPlugin.getData();

                }else{//该ID插件不存在，先清除redis缓存，在重新添加插件
                    //重新添加
                    Long id = IdWorker.getId();
                    sysPlugin = new SysPlugin();
                    sysPlugin.setId(pluginId);
                    sysPlugin.setMerId(configPlanPluginBatchUpdateDto.getMerId());
                    sysPlugin.setPlugName(plugName);
                    sysPlugin.setData(dataJSONObject_para.toJSONString());
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    sysPluginMapper.insert(sysPlugin);

                    //修改插件更新缓存，确保缓存和数据库一致
                    redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.PLUGIN.getKey(), sysPlugin.getId()) , sysPlugin.getData(), 5,TimeUnit.DAYS);

                    //其他插件内容
                    data_other = sysPlugin.getData();
                }
            }else{ //插件不存在, 新增插件，还得反射修改配置方案中对应的插件id
                Long id = IdWorker.getId();
                SysPlugin sysPlugin = new SysPlugin();
                sysPlugin.setId(id);
                sysPlugin.setMerId(configPlanPluginBatchUpdateDto.getMerId());
                sysPlugin.setPlugName(plugName);
                sysPlugin.setData(dataJSONObject_para.toJSONString());
                sysPlugin.setCreateTime(now);
                sysPlugin.setUpdateTime(now);
                sysPluginMapper.insert(sysPlugin);

                //修改插件更新缓存，确保缓存和数据库一致
                redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.PLUGIN.getKey(), sysPlugin.getId()) , sysPlugin.getData(), 5,TimeUnit.DAYS);

                //其他插件内容
                data_other = sysPlugin.getData();

                //反射配置方案类，设置对应的插件ID
                Tools.setValueByReflex(configPlan, configPlanPluginBatchUpdateDto.getPlugName(), id);
                //修改配置方案
                configPlanMapper.update(configPlan);

            }

            //如果是其他插件,需要将信息添加到Redis当中得 设备消息回复配置信息
            if("other".equals(plugName_hump)){
                //查询该所有使用过该配置得机器人
                DeviceQuery deviceQuery = new DeviceQuery();
                deviceQuery.setMerId(configPlan.getMerId());
                deviceQuery.setDeviceType(configPlan.getDeviceType());
                deviceQuery.setConfigId(configPlan.getId());
                List<DeviceInfoVo> deviceList = deviceService.findDeviceList(deviceQuery);
                if(deviceList != null && deviceList.size() > 0){
                    for (DeviceInfoVo deviceInfoVo : deviceList){
                        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_MSG_CONFIG.getKey(), deviceInfoVo.getId()) , data_other);
                    }
                }
            }

            //保存微信群基础设置
            if("group_baseset".equals(plugName)){
                //保存群基本设置数据缓存
                String redisKey_groupmanageplan = String.format(RedisCacheKeyEnum.WXQ_MANAGEPLAN.getKey(), configPlan.getId());
                redisTemplate.opsForValue().set(redisKey_groupmanageplan, dataJSONObject_para.toJSONString());
            }

            //修改指令
            robotCmdService.addRobotCmdForConfigPlan(configPlanPluginBatchUpdateDto.getMerId(), configPlanId, plugName, data_other);
            //更新指令redis缓存
            List<RobotCmd> robotCmdList = robotCmdMapper.selectByConfigId(configPlanPluginBatchUpdateDto.getMerId(), configPlanId);
            String data = Tools.getStrEmpty(JSONObject.toJSONString(robotCmdList));
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.COMMAND_LIST.getKey(), configPlanId), data);
        }
    }

    /**
     * 递归替换二个对象
     * @param jsonObject_old
     * @param jsonObject_new
     */
    public void replace(JSONObject jsonObject_old, JSONObject jsonObject_new){
        try{
            Set<String> keys = jsonObject_new.keySet();
            for (String key : keys) {
                Object value_new = jsonObject_new.get(key);
                Object value_old = jsonObject_old.get(key);
                //如果旧对象里没有，则以新的为主
                if(value_old == null){
                    jsonObject_old.put(key, value_new);
                }else{//不为空，则替换
                    if(value_new instanceof JSONObject){
                        JSONObject valueJsonObjec_new =  (JSONObject) value_new;
                        JSONObject valueJsonObject_old = (JSONObject) value_old;
                        //就对象里的值为空
                        if(valueJsonObject_old.isEmpty()){
                            jsonObject_old.put(key, valueJsonObjec_new);
                        }else{
                            replace(valueJsonObject_old, valueJsonObjec_new);
                        }
                    }else{//其他格式全部替换
                        jsonObject_old.put(key, value_new);
                    }
                }
            }
        }catch (Exception e){
        }
    }

    /**
     * 修改配置方案中的联盟
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param configPlanAccountUpdateDto
     * @return null
     */
    public void updateConfigPlanAccount(ConfigPlanAccountUpdateDto configPlanAccountUpdateDto){

        if(configPlanAccountUpdateDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        ConfigPlan configPlan = configPlanMapper.selectById(configPlanAccountUpdateDto.getId(), configPlanAccountUpdateDto.getMerId());

        if(configPlan == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该配置方案不存在");
        }

        //淘宝联盟ID
        configPlan.setTbAccountId(configPlanAccountUpdateDto.getTbAccountId());
        //淘宝炮灰订单类型
        configPlan.setPhTbOrderType(configPlanAccountUpdateDto.getPhTbOrderType());

        //唯品会联盟ID
        configPlan.setVphAccountType(configPlanAccountUpdateDto.getVphAccountType());
        configPlan.setVphAccountId(configPlanAccountUpdateDto.getVphAccountId());
        configPlan.setTlbVphAccountId(configPlanAccountUpdateDto.getTlbVphAccountId());
        //唯品会炮灰订单类型
        configPlan.setPhVphOrderType(configPlanAccountUpdateDto.getPhVphOrderType());

        //京东联盟ID
        configPlan.setJdAccountType(configPlanAccountUpdateDto.getJdAccountType());
        configPlan.setJdAccountId(configPlanAccountUpdateDto.getJdAccountId());
        configPlan.setTlbJdAccountId(configPlanAccountUpdateDto.getTlbJdAccountId());
        //京东炮灰订单类型
        configPlan.setPhJdOrderType(configPlanAccountUpdateDto.getPhJdOrderType());

        //拼多多账号类型（0自有账号，1推老板共享账号）
        configPlan.setPddAccountType(configPlanAccountUpdateDto.getPddAccountType());
        //拼多多联盟账号
        configPlan.setPddAccountId(configPlanAccountUpdateDto.getPddAccountId());
        //拼多多共享推老板账号
        configPlan.setTlbPddAccountId(configPlanAccountUpdateDto.getTlbPddAccountId());

        //美团账号类型（0自有账号，1推老板共享账号）
        configPlan.setMtAccountType(configPlanAccountUpdateDto.getMtAccountType());
        //美团共享推老板联盟
        configPlan.setTlbMtAccountId(configPlanAccountUpdateDto.getTlbMtAccountId());

        //饿了么联盟id
        configPlan.setElmAccountType(configPlanAccountUpdateDto.getElmAccountType());
        configPlan.setElmAccountId(configPlanAccountUpdateDto.getElmAccountId());
        configPlan.setTlbElmAccountId(configPlanAccountUpdateDto.getTlbElmAccountId());

        //抖音联盟
        configPlan.setDyAccountId(configPlanAccountUpdateDto.getDyAccountId());
        //抖音共享推老板联盟
        configPlan.setTlbDyAccountId(configPlanAccountUpdateDto.getTlbDyAccountId());
        //抖音账号类型（0自有账号，1推老板共享账号）
        configPlan.setDyAccountType(configPlanAccountUpdateDto.getDyAccountType());
        //抖音炮灰订单类型（0付款，1结算）
        configPlan.setPhDyOrderType(configPlanAccountUpdateDto.getPhDyOrderType());

        //快手联盟
        configPlan.setKsAccountId(configPlanAccountUpdateDto.getKsAccountId());
        //快手共享推老板联盟
        configPlan.setTlbKsAccountId(configPlanAccountUpdateDto.getTlbKsAccountId());
        //快手账号类型（0自有账号，1推老板共享账号）
        configPlan.setKsAccountType(configPlanAccountUpdateDto.getKsAccountType());
        //快手炮灰订单类型（0付款，1结算）
        configPlan.setPhKsOrderType(configPlanAccountUpdateDto.getPhKsOrderType());

        //修改配置方案
        configPlanMapper.update(configPlan);

    }

    /**
     * 批量修改配置方案中的联盟
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param configPlanAccountBatchUpdateDto
     * @return null
     */
    @Transactional
    public void batchUpdateConfigPlanAccount(ConfigPlanAccountBatchUpdateDto configPlanAccountBatchUpdateDto){
        List<Long> configPlanIdList = configPlanAccountBatchUpdateDto.getConfigPlanIDList();
        if(configPlanIdList == null || configPlanIdList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        if(StringUtils.isBlank(configPlanAccountBatchUpdateDto.getData())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        JSONObject dataJSONObject = JSONObject.parseObject(configPlanAccountBatchUpdateDto.getData());
        if(dataJSONObject == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        Set<String> keySet =  dataJSONObject.keySet();
        if(keySet == null || keySet.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        for (Long configPlanId : configPlanIdList){
            ConfigPlan configPlan = configPlanMapper.selectById(configPlanId, configPlanAccountBatchUpdateDto.getMerId());
            if(configPlan != null){
                for (String key : keySet){
                    Object value = dataJSONObject.get(key);
                    //反射配置方案类，设置对应的插件ID
                    Class cls = configPlan.getClass();
                    Field field = null;
                    try {
                        field = cls.getDeclaredField(key);
                        field.setAccessible(true);//设置允许访问
                        field.set(configPlan, value);
                        //修改配置方案
                        configPlanMapper.update(configPlan);
                    } catch (Exception e) {
                    }
                }
            }
        }
    }


    /**
     * 修改配置方案中的分佣
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param configPlanProfitUpdateDto
     * @return null
     */
    public void updateConfigPlanProfit(ConfigPlanProfitUpdateDto configPlanProfitUpdateDto){

        if(configPlanProfitUpdateDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        ConfigPlan configPlan = configPlanMapper.selectById(configPlanProfitUpdateDto.getId(), configPlanProfitUpdateDto.getMerId());

        if(configPlan == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该配置方案不存在");
        }

        //用户会员组
        if(configPlanProfitUpdateDto.getUserTypeGroupId() != null){
            if(Tools.getLong(configPlan.getUserTypeGroupId()).longValue() != 0){ //已经配置了会员类型组
                //验证是否修改了会员类型组，如果修改了，则需要判断该会员类型组内的任一会员类型是否有用户使用，如果有，则不允许修改
                if(Tools.getLong(configPlan.getUserTypeGroupId()).longValue() != configPlanProfitUpdateDto.getUserTypeGroupId().longValue()){
                    //查询该会员类型组内所有的会员类型
                    UserTypeQuery userTypeQuery = new UserTypeQuery();
                    userTypeQuery.setMerId(configPlanProfitUpdateDto.getMerId());
                    userTypeQuery.setGroupId(configPlan.getUserTypeGroupId());
                    List<UserType> userTypeList = userTypeMapper.findByList(userTypeQuery);
                    if(userTypeList != null && userTypeList.size() > 0){
                        //查询该类型组内所有的会员类型是否有用户在使用，如果在使用，则不允许修改
                        WechatUserQuery wechatUserQuery = new WechatUserQuery();
                        wechatUserQuery.setMerId(configPlanProfitUpdateDto.getMerId());
                        List<Long> userTypeIdList = new ArrayList<>();
                        for (UserType userType: userTypeList) {
                            userTypeIdList.add(userType.getId());
                        }
                        wechatUserQuery.setUserTypeList(userTypeIdList);
                        Page<WechatUser> page = new Page<>();
                        page.setSize(5);
                        page.setCurrent(1);
                        List<WechatUser> wechatUserList =   wechatUserMapper.findByList(page, wechatUserQuery);
                        //表示有用户在使用该组内的会员类型
                        if(wechatUserList != null && wechatUserList.size() > 0){
                            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "已经有用户使用了该配置方案的会员类型组内的会员类型，仅支持修改当前会员类型组的分佣规则");
                        }
                    }
                }
            }
        }

        //用户会员组
        configPlan.setUserTypeGroupId(configPlanProfitUpdateDto.getUserTypeGroupId());

        //淘宝分佣规则ID
        configPlan.setTbCommissionPlanId(configPlanProfitUpdateDto.getTbCommissionPlanId());

        //京东分佣方案ID
        configPlan.setJdCommissionPlanId(configPlanProfitUpdateDto.getJdCommissionPlanId());

        //拼多多分佣方案
        configPlan.setPddCommissionPlanId(configPlanProfitUpdateDto.getPddCommissionPlanId());

        //唯品会分佣方案
        configPlan.setVphCommissionPlanId(configPlanProfitUpdateDto.getVphCommissionPlanId());

        //本地生活分佣方案
        configPlan.setLocalLiveCommissionPlanId(configPlanProfitUpdateDto.getLocalLiveCommissionPlanId());

        //抖音分佣方案
        configPlan.setDyCommissionPlanId(configPlanProfitUpdateDto.getDyCommissionPlanId());

        //快手分佣方案
        configPlan.setKsCommissionPlanId(configPlanProfitUpdateDto.getKsCommissionPlanId());

        //修改配置方案
        configPlanMapper.update(configPlan);

    }

    /**
     * 查询淘宝联盟下拉选择列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbTokenQuery
     * @return null
     */
    public List<SelectIdVo> findTbTokenSelectList(TbTokenQuery tbTokenQuery){
        //tbTokenQuery.setIsPh(0); //是否为炮灰账号(0否，1是)
        tbTokenQuery.setType(0); //类型：0淘宝，1饿了么
        List<TbToken> tbTtkenList = tbTokenMapper.findByList(tbTokenQuery);

        //新建返回页面对象
        List<SelectIdVo> tbTokenVoList = new ArrayList<SelectIdVo>();
        if(tbTtkenList != null ){
            for (TbToken tbToken : tbTtkenList) {
                if(tbToken.getIsAux().intValue() == 0){ //不是辅助账号
                    SelectIdVo  SelectIdVo = new SelectIdVo();
                    SelectIdVo.setKey(tbToken.getId());
                    //备注
                    String remark = tbToken.getRemark();
                    if(Tools.getInteger(tbToken.getTurnlink()).intValue() == 1){
                        if(StringUtils.isNotBlank(tbToken.getRemark())){
                            remark =  "导购_" + remark;
                        }else{
                            remark =   "导购";
                        }
                    }else{
                        if(StringUtils.isNotBlank(tbToken.getRemark())){
                            remark =  "返利_" + remark;
                        }else{
                            remark =   "返利";
                        }
                    }
                    String value = tbToken.getUserName();
                    if(StringUtils.isNotBlank(remark)){
                        value = value + "（" + remark + "）";
                    }
                    SelectIdVo.setValue(value);
                    tbTokenVoList.add(SelectIdVo);
                }
            }
        }
        return tbTokenVoList;
    }

    /**
     * 查询淘宝联盟下拉选择列表(取值token)
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tbTokenQuery
     * @return null
     */
    public List<SelectKeyVo> findTbTokenValueSelectList(TbTokenQuery tbTokenQuery){
        //tbTokenQuery.setIsPh(0); //是否为炮灰账号(0否，1是)
        tbTokenQuery.setType(0); //类型：0淘宝，1饿了么
        List<TbToken> tbTtkenList = tbTokenMapper.findByList(tbTokenQuery);

        //新建返回页面对象
        List<SelectKeyVo> tbTokenVoList = new ArrayList<>();
        if(tbTtkenList != null ){
            for (TbToken tbToken : tbTtkenList) {
                if(tbToken.getIsAux().intValue() == 0){ //不是辅助账号
                    SelectKeyVo  selectKeyVo = new SelectKeyVo();
                    selectKeyVo.setKey(tbToken.getAccessToken());
                    //备注
                    String remark = tbToken.getRemark();
                    if(Tools.getInteger(tbToken.getTurnlink()).intValue() == 1){
                        if(StringUtils.isNotBlank(tbToken.getRemark())){
                            remark =  "导购_" + remark;
                        }else{
                            remark =   "导购";
                        }
                    }else{
                        if(StringUtils.isNotBlank(tbToken.getRemark())){
                            remark =  "返利_" + remark;
                        }else{
                            remark =   "返利";
                        }
                    }
                    String value = tbToken.getUserName();
                    if(StringUtils.isNotBlank(remark)){
                        value = value + "（" + remark + "）";
                    }
                    selectKeyVo.setValue(value);
                    tbTokenVoList.add(selectKeyVo);
                }
            }
        }
        return tbTokenVoList;
    }

    /**
     * 查询饿了么联盟下拉选择列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @return null
     */
    public List<SelectIdVo> findElmTokenSelectList(Long merId){
        TbTokenQuery tbTokenQuery = new TbTokenQuery();
        tbTokenQuery.setMerId(merId);
        //tbTokenQuery.setIsPh(0); //是否为炮灰账号(0否，1是)
        tbTokenQuery.setType(1); //类型：0淘宝，1饿了么
        List<TbToken> tbTtkenList = tbTokenMapper.findByList(tbTokenQuery);

        //新建返回页面对象
        List<SelectIdVo> tbTokenVoList = new ArrayList<SelectIdVo>();
        if(tbTtkenList != null ){
            for (TbToken tbToken : tbTtkenList) {
                if(tbToken.getIsAux().intValue() == 0) { //不是辅助账号
                    SelectIdVo  SelectIdVo = new SelectIdVo();
                    SelectIdVo.setKey(tbToken.getId());

                    //备注
                    String remark = tbToken.getRemark();
                    if(Tools.getInteger(tbToken.getTurnlink()).intValue() == 1){
                        if(StringUtils.isNotBlank(tbToken.getRemark())){
                            remark =  "导购_" + remark;
                        }else{
                            remark =   "导购";
                        }
                    }else{
                        if(StringUtils.isNotBlank(tbToken.getRemark())){
                            remark =  "返利_" + remark;
                        }else{
                            remark =   "返利";
                        }
                    }
                    String value = tbToken.getUserName();
                    if(StringUtils.isNotBlank(remark)){
                        value = value + "（" + remark + "）";
                    }
                    SelectIdVo.setValue(value);

                    tbTokenVoList.add(SelectIdVo);
                }
            }
        }
        return tbTokenVoList;
    }

    /**
     * 查询炮灰淘宝联盟下拉列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @return null
     */
    public List<SelectIdVo> findPhTbTokenSelectList(Long merId){
        TbTokenQuery tbTokenQuery = new TbTokenQuery();
        tbTokenQuery.setMerId(merId);
        //tbTokenQuery.setIsPh(1); //是否为炮灰账号(0否，1是)
        tbTokenQuery.setType(0); //类型：0淘宝，1饿了么
        List<TbToken> tbTtkenList = tbTokenMapper.findByList(tbTokenQuery);
        //新建返回页面对象
        List<SelectIdVo> tbTokenVoList = new ArrayList<SelectIdVo>();
        if(tbTtkenList != null ){
            for (TbToken tbToken : tbTtkenList) {
                SelectIdVo  SelectIdVo = new SelectIdVo();
                SelectIdVo.setKey(tbToken.getId());
                //备注
                String remark = tbToken.getRemark();
                if(Tools.getInteger(tbToken.getTurnlink()).intValue() == 1){
                    if(StringUtils.isNotBlank(tbToken.getRemark())){
                        remark =  "导购_" + remark;
                    }else{
                        remark =   "导购";
                    }
                }else{
                    if(StringUtils.isNotBlank(tbToken.getRemark())){
                        remark =  "返利_" + remark;
                    }else{
                        remark =   "返利";
                    }
                }
                String value = tbToken.getUserName();
                if(StringUtils.isNotBlank(remark)){
                    value = value + "（" + remark + "）";
                }
                SelectIdVo.setValue(value);
                tbTokenVoList.add(SelectIdVo);
            }
        }
        return tbTokenVoList;
    }

    /**
     * 查询唯品会联盟下拉选择列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @return null
     */
    public List<SelectIdVo> findVphTokenSelectList(Long merId){
        //新建返回页面对象
        List<SelectIdVo> vphTokenVoList = new ArrayList<SelectIdVo>();

        VphTokenQuery vphTokenQuery = new VphTokenQuery();
        vphTokenQuery.setMerId(merId);
        //vphTokenQuery.setIsPh(0);
        List<VphToken> vphTokenList = vphTokenMapper.findByList(vphTokenQuery);
        if(vphTokenList != null){
            for (VphToken vphToken : vphTokenList) {
                SelectIdVo  SelectIdVo = new SelectIdVo();
                SelectIdVo.setKey(vphToken.getId());
                //备注
                String remark = vphToken.getRemark();
                String value = vphToken.getOpenId();
                if(StringUtils.isNotBlank(remark)){
                    value = value + "（" + remark + "）";
                }
                SelectIdVo.setValue(value);
                vphTokenVoList.add(SelectIdVo);
            }
        }
        return vphTokenVoList;
    }

    /**
     * 查询炮灰唯品会联盟下拉选择列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @return null
     */
    public List<SelectIdVo> findPhVphTokenSelectList(Long merId){
        //新建返回页面对象
        List<SelectIdVo> vphPhTokenVoList = new ArrayList<SelectIdVo>();

        VphTokenQuery vphTokenQuery = new VphTokenQuery();
        vphTokenQuery.setMerId(merId);
        //vphTokenQuery.setIsPh(1);
        List<VphToken> vphTokenList = vphTokenMapper.findByList(vphTokenQuery);
        if(vphTokenList != null){
            for (VphToken vphToken : vphTokenList) {
                SelectIdVo  SelectIdVo = new SelectIdVo();
                SelectIdVo.setKey(vphToken.getId());

                //备注
                String remark = vphToken.getRemark();
                String value = vphToken.getOpenId();
                if(StringUtils.isNotBlank(remark)){
                    value = value + "（" + remark + "）";
                }
                SelectIdVo.setValue(value);

                vphPhTokenVoList.add(SelectIdVo);
            }
        }
        return vphPhTokenVoList;
    }

    /**
     * 查询京东联盟下拉选择列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @return null
     */
    public List<SelectIdVo> findJdTokenSelectList(Long merId){
        //新建返回页面对象
        List<SelectIdVo> jdTokenVoList = new ArrayList<>();

        JdTokenQuery jdTokenQuery = new JdTokenQuery();
        jdTokenQuery.setMerId(merId);
        List<JdToken> jdTokenList = jdTokenMapper.findByList(jdTokenQuery);
        if(jdTokenList != null){
            for (JdToken jdToken : jdTokenList) {
                SelectIdVo  SelectIdVo = new SelectIdVo();
                SelectIdVo.setKey(jdToken.getId());

                //备注
                String remark = jdToken.getRemark();
                String value = jdToken.getUnionId();
                if(StringUtils.isNotBlank(remark)){
                    value = value + "（" + remark + "）";
                }
                SelectIdVo.setValue(value);

                jdTokenVoList.add(SelectIdVo);
            }
        }

        return jdTokenVoList;
    }

    /**
     * 查询京东联盟下拉选择列表(取值京东联盟unionid)
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @return null
     */
    public List<SelectKeyVo> findJdTokenValueSelectList(Long merId){
        //新建返回页面对象
        List<SelectKeyVo> jdTokenVoList = new ArrayList<>();
        JdTokenQuery jdTokenQuery = new JdTokenQuery();
        jdTokenQuery.setMerId(merId);
        List<JdToken> jdTokenList = jdTokenMapper.findByList(jdTokenQuery);
        if(jdTokenList != null){
            for (JdToken jdToken : jdTokenList) {
                SelectKeyVo  selectKeyVo = new SelectKeyVo();
                selectKeyVo.setKey(jdToken.getUnionId());

                //备注
                String remark = jdToken.getRemark();
                String value = jdToken.getUnionId();
                if(StringUtils.isNotBlank(remark)){
                    value = value + "（" + remark + "）";
                }
                selectKeyVo.setValue(value);

                jdTokenVoList.add(selectKeyVo);
            }
        }
        return jdTokenVoList;
    }

    /**
     * 查询拼多多联盟下拉选择列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @return null
     */
    public List<SelectIdVo> findPddTokenSelectList(Long merId){
        //新建返回页面对象
        List<SelectIdVo> pddTokenVoList = new ArrayList<SelectIdVo>();

        PddTokenQuery pddTokenQuery = new PddTokenQuery();
        pddTokenQuery.setMerId(merId);
        List<PddToken> pddTokenList = pddTokenMapper.findByList(pddTokenQuery);
        if(pddTokenList != null){
            for (PddToken pddToken : pddTokenList) {
                SelectIdVo  selectIdVo = new SelectIdVo();
                selectIdVo.setKey(pddToken.getId());

                //备注
                String remark = pddToken.getRemark();
                String value = pddToken.getUserName();
                if(StringUtils.isNotBlank(remark)){
                    value = value + "（" + remark + "）";
                }
                selectIdVo.setValue(value);

                //封装拼多多的免单备案链接
                selectIdVo.setPddMdRecordUrl(pddToken.getMdRecordUrl());

                pddTokenVoList.add(selectIdVo);
            }
        }
        return pddTokenVoList;
    }

    /**
     * 查询抖音联盟下拉选择列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @return null
     */
    public List<SelectIdVo> findDyTokenSelectList(Long merId){
        //新建返回页面对象
        List<SelectIdVo> dyTokenVoList = new ArrayList<SelectIdVo>();

        DyTokenQuery dyTokenQuery = new DyTokenQuery();
        dyTokenQuery.setMerId(merId);
        List<DyToken> dyTokenList = dyTokenMapper.findByList(dyTokenQuery);
        if(dyTokenList != null){
            for (DyToken dyToken : dyTokenList) {
                SelectIdVo  selectIdVo = new SelectIdVo();
                selectIdVo.setKey(dyToken.getId());

                //备注
                String remark = dyToken.getRemark();
                String value = dyToken.getName();
                if(StringUtils.isNotBlank(remark)){
                    value = value + "（" + remark + "）";
                }
                selectIdVo.setValue(value);

                dyTokenVoList.add(selectIdVo);
            }
        }
        return dyTokenVoList;
    }


    /**
     * 查询推老板共享账号下拉选择列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param tlbTokenQuery
     * @return null
     */
    public List<SelectIdVo> findTlbTokenSelectList(TlbTokenQuery tlbTokenQuery){
        //新建返回页面对象
        List<SelectIdVo> tlbTokenVoList = new ArrayList<SelectIdVo>();
        //循环推老板联盟账户
        List<TlbToken> tlbTokenList = tlbTokenMapper.findByList(tlbTokenQuery);
        if(tlbTokenList != null){
            for (TlbToken tlbToken : tlbTokenList){
                SelectIdVo  selectIdVo = new SelectIdVo();
                selectIdVo.setKey(tlbToken.getId());

                //备注
                String remark = tlbToken.getRemark();
                String value = tlbToken.getAppId();
                if(StringUtils.isNotBlank(remark)){
                    value = value + "（" + remark + "）";
                }
                selectIdVo.setValue(value);

                tlbTokenVoList.add(selectIdVo);
            }
        }
        return tlbTokenVoList;
    }



    /**
     * 查询推广裂变的奖励方案下拉选择列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @return null
     */
    public List<SelectIdVo> findRegRewardRuleSelectList(Long merId){
        //新建返回页面对象
        List<SelectIdVo> regRewardRuleVoList = new ArrayList<SelectIdVo>();
        RegRewardRuleQuery regRewardRuleQuery = new RegRewardRuleQuery();
        regRewardRuleQuery.setMerId(merId);
        List<RegRewardRule> regRewardRuleList =  regRewardRuleMapper.findByList(regRewardRuleQuery);
        if(regRewardRuleList != null && regRewardRuleList.size() > 0){
            for (RegRewardRule regRewardRule : regRewardRuleList) {
                SelectIdVo  SelectIdVo = new SelectIdVo();
                SelectIdVo.setKey(regRewardRule.getId());
                SelectIdVo.setValue(regRewardRule.getName());
                regRewardRuleVoList.add(SelectIdVo);
            }
        }
        return regRewardRuleVoList;
    }

    /**
     * 查询域名下拉选择列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @return null
     */
    public List<SysDomainInfoVo> findSysDomainSelectList(Long merId){
        //新建返回页面对象
        List<SysDomainInfoVo> sysDomainInfoVoList = new ArrayList<>();
        SysDomainQuery sysDomainQuery = new SysDomainQuery();
        sysDomainQuery.setMerId(merId);
        sysDomainQuery.setStatus(1);
        List<SysDomain> sysDomainList =  sysDomainMapper.findByList(sysDomainQuery);
        if(sysDomainList != null && sysDomainList.size() > 0){
            for (SysDomain sysDomain : sysDomainList) {
                SysDomainInfoVo  sysDomainInfoVo = new SysDomainInfoVo();
                BeanUtils.copyProperties(sysDomain, sysDomainInfoVo);
                sysDomainInfoVoList.add(sysDomainInfoVo);
            }
        }
        return sysDomainInfoVoList;
    }

    /**
     * 查询分佣规则下拉选择列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param configPlanNormalrewardruleDto
     * @return null
     */
    public List<SelectIdVo> findNormalRewardRuleSelectList(ConfigPlanNormalrewardruleDto configPlanNormalrewardruleDto){
        //新建返回页面对象
        List<SelectIdVo> normalRewardRuleVoList = new ArrayList<SelectIdVo>();
        NormalRewardRuleQuery normalRewardRuleQuery = new NormalRewardRuleQuery();
        normalRewardRuleQuery.setMerId(configPlanNormalrewardruleDto.getMerId());
        normalRewardRuleQuery.setUserTypeGroupId(configPlanNormalrewardruleDto.getUserTypeGroupId());
        List<NormalRewardRule> normalRewardRuleList = normalRewardRuleMapper.findByList(normalRewardRuleQuery);
        if(normalRewardRuleList != null) {
            for (NormalRewardRule normalRewardRule : normalRewardRuleList) {
                SelectIdVo SelectIdVo = new SelectIdVo();
                SelectIdVo.setKey(normalRewardRule.getId());
                SelectIdVo.setValue(normalRewardRule.getName());
                normalRewardRuleVoList.add(SelectIdVo);
            }
        }
        return normalRewardRuleVoList;
    }

    @Override
    public ConfigPlanSelectListVo findAppConfigPlan(ConfigPlanQuery query) {
        //查询数据库中的配置方案
        ConfigPlan configPlan = configPlanMapper.selectAppConfigPlan(query.getMerId());
        if (Objects.isNull(configPlan)) {
            configPlan = init(query.getMerId());
        }
        ConfigPlanSelectListVo selectListVo = new ConfigPlanSelectListVo();
        BeanUtils.copyProperties(configPlan, selectListVo);

        // 根据运营商查询机器人ID
        DeviceAppInfo deviceAppInfo = appDeviceInfoService.getByMerId(query.getMerId());
        if (Objects.isNull(deviceAppInfo)) {
            deviceAppInfo = appDeviceInfoService.init(configPlan.getMerId());
        }
        deviceAppInfo.setConfigId(configPlan.getId());
        appDeviceInfoService.update(deviceAppInfo);
        // 获取缓存
        String cacheKey = String.format(RedisCacheKeyEnum.DEVICE_INFO_APP.getKey(), deviceAppInfo.getId());
        // 设置缓存
        redisTemplate.opsForValue().set(cacheKey, JSON.toJSONString(deviceAppInfo));
        return selectListVo;
    }

    public ConfigPlan init(Long currentMerId) {
        //新建配置方案id
        Long configPlanIdNew = IdWorker.getId();
        //当前时间
        int now = (int) (System.currentTimeMillis() / 1000L);

        //复制默认运营商id
        Long sourceMerId = uzaiConsoleSysConfig.getDefaultMerId();
        //查询默认运营商APP配置方案
        ConfigPlan configPlan = configPlanMapper.selectAppConfigPlan(sourceMerId);
        if(configPlan != null){
            //复制插件件信息
            List<SysPlugin> sysPluginsList = new ArrayList<>();
            //淘宝插件ID
            if(configPlan.getTbId() != null ){
                //查询淘宝插件
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getTbId(), configPlan.getMerId());
                if(sysPlugin != null){
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(currentMerId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案的淘宝插件
                    configPlan.setTbId(id);
                }
            }

            //京东插件id
            if(configPlan.getJdId()!= null ){
                //查询京东插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getJdId(), configPlan.getMerId());
                if(sysPlugin != null){
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(currentMerId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加京东插件id
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案的京东插件id
                    configPlan.setJdId(id);
                }
            }

            //拼多多插件id
            if(configPlan.getPddId()!= null ){
                //查询拼多多插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getPddId(), configPlan.getMerId());
                if(sysPlugin != null){
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(currentMerId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加拼多多插件id
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案的拼多多插件id
                    configPlan.setPddId(id);
                }
            }

            //唯品会插件id
            if(configPlan.getVphId()!= null ){
                //查询唯品会插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getVphId(), configPlan.getMerId());
                if(sysPlugin != null){
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(currentMerId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加唯品会插件id
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案的唯品会插件id
                    configPlan.setVphId(id);
                }
            }

            //抖音插件id
            if(configPlan.getDyId()!= null ){
                //查询唯品会插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getDyId(), configPlan.getMerId());
                if(sysPlugin != null){
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加唯品会插件id
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案的唯品会插件id
                    configPlan.setDyId(id);
                }
            }

            //本地生活插件id
            if(configPlan.getLocalLiveId()!= null ){
                //查询本地生活插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getLocalLiveId(), configPlan.getMerId());
                if(sysPlugin != null){
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(currentMerId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加本地生活插件id
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案的本地生活插件id
                    configPlan.setLocalLiveId(id);
                }
            }

            //微信好友添加插件id
            if(configPlan.getWxUserAddId()!= null ){
                //查询微信好友添加插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getWxUserAddId(), configPlan.getMerId());
                if(sysPlugin != null){
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(currentMerId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加微信好友添加插件id
                    //sysPluginMapper.insert(sysPlugin);
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案的微信好友添加插件id
                    configPlan.setWxUserAddId(id);
                }
            }

            //推广裂变插件id
            if(configPlan.getUserExpandFissionId()!= null ){
                //查询推广裂变插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserExpandFissionId(), configPlan.getMerId());
                if(sysPlugin != null){
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(currentMerId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加推广裂变插件id
                    //sysPluginMapper.insert(sysPlugin);
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案的推广裂变插件id
                    configPlan.setUserExpandFissionId(id);
                }
            }

            //提现插件id
            if(configPlan.getUserTakeBalId()!= null ){
                //查询提现插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserTakeBalId(), configPlan.getMerId());
                if(sysPlugin != null){
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(currentMerId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加提现插件id
                    //sysPluginMapper.insert(sysPlugin);
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案中提现插件id

                    //清空提现账房信息-每个运营商账房信息不一样
                    String data = sysPlugin.getData();
                    if(StringUtils.isNotBlank(data)){
                        try {
                            JSONObject jsonObject = JSONObject.parseObject(data);
                            if(jsonObject != null){
                                jsonObject.put("zf_app_id", "");
                                jsonObject.put("zf_app_key", "");
                                jsonObject.put("wxpay_zf_app_id", "");
                                jsonObject.put("wxpay_zf_app_key", "");
                            }
                            sysPlugin.setData(JSONObject.toJSONString(jsonObject));
                        }catch (Exception e){
                            logger.error("-提现插件转成JSON对象出错--,errror={}", e.getMessage());
                        }

                    }
                    configPlan.setUserTakeBalId(id);
                }
            }

            //好友引导插件id
            if(configPlan.getUserGuideId()!= null ){
                //好友引导插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserGuideId(), configPlan.getMerId());
                if(sysPlugin != null){
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(currentMerId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加好友引导插件id
                    //sysPluginMapper.insert(sysPlugin);
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案中好友引导插件id
                    configPlan.setUserGuideId(id);
                }
            }

            //自动备注插件id
            if(configPlan.getUserAutoRemarkId()!= null ){
                //自动备注插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserAutoRemarkId(), configPlan.getMerId());
                if(sysPlugin != null){
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(currentMerId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加自动备注插件id
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案中自动备注插件id
                    configPlan.setUserAutoRemarkId(id);
                }
            }

            //订阅消息插件id
            if(configPlan.getSubscribeMsgId()!= null ){
                //订阅消息插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getSubscribeMsgId(), configPlan.getMerId());
                if(sysPlugin != null){
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(currentMerId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加订阅消息插件id
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案中订阅消息插件id
                    configPlan.setSubscribeMsgId(id);
                }
            }

            //个人信息查询插件id
            if(configPlan.getUserInfoQueryId()!= null ){
                //订阅消息插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserInfoQueryId(), configPlan.getMerId());
                if(sysPlugin != null){
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(currentMerId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加个人信息查询插件id
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案中个人信息查询插件id
                    configPlan.setUserInfoQueryId(id);
                }
            }

            //用户签到插件id
            if(configPlan.getUserSigninId()!= null ){
                //用户签到插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserSigninId(), configPlan.getMerId());
                if(sysPlugin != null){
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(currentMerId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加用户签到插件id
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案中用户签到插件id
                    configPlan.setUserSigninId(id);
                }
            }

            //社群管理插件id
            if(configPlan.getCommunityId()!= null ){
                //社群管理插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getCommunityId(), configPlan.getMerId());
                if(sysPlugin != null){
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(currentMerId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加社群管理插件id
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案中社群管理插件id
                    configPlan.setCommunityId(id);
                }
            }

            //导购插件id
            if(configPlan.getShoppingGuideId() != null ){
                //社群管理插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getShoppingGuideId(), configPlan.getMerId());
                if(sysPlugin != null){
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(currentMerId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加社群管理插件id
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案中社群管理插件id
                    configPlan.setShoppingGuideId(id);
                }
            }

            //其他设置插件id
            if(configPlan.getOtherId()!= null ){
                //其他设置插件id
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getOtherId(), configPlan.getMerId());
                if(sysPlugin != null){
                    Long id = IdWorker.getId();
                    sysPlugin.setId(id);
                    sysPlugin.setMerId(currentMerId);
                    sysPlugin.setCreateTime(now);
                    sysPlugin.setUpdateTime(now);
                    //新加其他设置插件id
                    sysPluginsList.add(sysPlugin);
                    //修改配置方案中其他设置插件id
                    configPlan.setOtherId(id);
                }
            }

            //批量插入插件
            if(sysPluginsList != null & sysPluginsList.size() > 0){
                sysPluginMapper.batchAdd(sysPluginsList);
                for(SysPlugin sysPlugin : sysPluginsList){
                    //修改插件更新缓存，确保缓存和数据库一致
                    redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.PLUGIN.getKey(), sysPlugin.getId()) , sysPlugin.getData(), 5, TimeUnit.DAYS);
                }
            }

            //查出旧指令列表
            List<RobotCmd> robotCmdList = robotCmdMapper.selectByConfigId(configPlan.getMerId(), configPlan.getId());
            if(robotCmdList != null && robotCmdList.size() > 0){
                for (RobotCmd robotCmd : robotCmdList){
                    robotCmd.setId(IdWorker.getId()); //更新旧指令ID
                    robotCmd.setMerId(currentMerId);
                    robotCmd.setConfigId(configPlanIdNew);//更新旧指令配置方案
                    robotCmd.setCreateTime(now);
                    robotCmd.setUpdateTime(now);
                }

                //批量插入指令表数据库
                robotCmdMapper.batchAdd(robotCmdList);

                //更新新的指令缓存redis
                String data = Tools.getStrEmpty(JSONObject.toJSONString(robotCmdList));
                redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.COMMAND_LIST.getKey(), configPlanIdNew), data);

            }

            //更新分佣规则
            //查询此运营商默认的分佣规则
            NormalRewardRule normalRewardRuleDefault = normalRewardRuleMapper.selectByIsDefault(currentMerId);
            if(normalRewardRuleDefault != null){
                //会员类型组
                configPlan.setUserTypeGroupId(normalRewardRuleDefault.getUserTypeGroupId());
                //淘宝分佣规则
                configPlan.setTbCommissionPlanId(normalRewardRuleDefault.getId());
                //京东分佣规则
                configPlan.setJdCommissionPlanId(normalRewardRuleDefault.getId());
                //拼多多分佣规则
                configPlan.setPddCommissionPlanId(normalRewardRuleDefault.getId());
                //唯品会分佣规则
                configPlan.setVphCommissionPlanId(normalRewardRuleDefault.getId());
                //抖音分佣规则
                configPlan.setDyCommissionPlanId(normalRewardRuleDefault.getId());
                //本地生活分佣规则
                configPlan.setLocalLiveCommissionPlanId(normalRewardRuleDefault.getId());
                //
            }else{ //如果没有默认的分佣规则，则清空分佣规则
                //会员类型组
                configPlan.setUserTypeGroupId(null);
                //淘宝分佣规则
                configPlan.setTbCommissionPlanId(null);
                //京东分佣规则
                configPlan.setJdCommissionPlanId(null);
                //拼多多分佣规则
                configPlan.setPddCommissionPlanId(null);
                //唯品会分佣规则
                configPlan.setVphCommissionPlanId(null);
                //抖音分佣规则
                configPlan.setDyCommissionPlanId(null);
                //本地生活分佣规则
                configPlan.setLocalLiveCommissionPlanId(null);
            }

            //清除联盟设置
            configPlan.setTbAccountId(null);
            configPlan.setJdAccountId(null);
            configPlan.setPddAccountId(null);
            configPlan.setVphAccountId(null);
            configPlan.setTlbPddAccountId(null);
            configPlan.setTlbMtAccountId(null);
            configPlan.setElmAccountId(null);
            configPlan.setTlbElmAccountId(null);
            configPlan.setDyAccountId(null);

        }else{ //新建配置方案
            configPlan = new ConfigPlan();

        }

        //修改id
        configPlan.setId(configPlanIdNew);
        configPlan.setMerId(currentMerId);
        configPlan.setDeviceType(DeviceTypeEnum.APP.getKey());
        configPlan.setName("APP默认配置方案");
        configPlan.setIsDefault(1); //默认
        configPlan.setCreateTime(now);
        configPlan.setUpdateTime(now);

        configPlanMapper.insert(configPlan);
        return configPlan;
    }

    /**
     * 获取大促配置信息
     * @author lucher
     * @date 2023/6/28 11:01
     * @return com.uzai.console.vo.wechatprivate.configplan.BigPromotionVo
     */
    public BigPromotionVo findBigPromotionInfo(){
        BigPromotionVo bigPromotionVo = new BigPromotionVo();

        Object object = redisTemplate.opsForValue().get(RedisCacheKeyEnum.GREAT_PROMOTION_MIDDLE_PAGE_LINK.getKey());
        if(object == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "为获取到大促配置信息");
        }else{
            String greatPromotionMiddlePageLink = object.toString();
            bigPromotionVo.setGreatPromotionMiddlePageLink(greatPromotionMiddlePageLink);
        }

        return bigPromotionVo;
    }

}
